gpt4 book ai didi

c - 如何重新分配内部和外部数组

转载 作者:太空狗 更新时间:2023-10-29 15:22:21 25 4
gpt4 key购买 nike

所以,我接到了一个奇怪的任务。我必须将文件内容读取到数组字符串中。但是,我必须像这样初始化数组(我必须将其初始化为数组大小 1):

char **input = (char **)malloc(1*sizeof(char*))

代替

char **input = (char **)malloc((sizeOfFile+1)*sizeof(char*))

所以,我必须继续使用 realloc。我的问题是,如何重新分配内部数组(字符串)以及如何重新分配外部数组(字符串数组)

最佳答案

您不必重新分配“内部数组”。您分配的内存内容是指针,当您重新分配 input 时,您只会重新分配 input 指针,而不是 where input 的内容> 指向。


展示其工作原理的粗略 ASCII 图像:

首先,当您在 input 数组中分配一个条目时,它看起来像这样:

         +----------+    +---------------------------+
input -> | input[0] | -> | What `input[0]` points to |
+----------+ +---------------------------+

在你重新分配为第二个条目腾出空间之后(即 input = realloc(input, 2 * sizeof(char*));)

         +----------+    +---------------------------+
input -> | input[0] | -> | What `input[0]` points to |
+----------+ +---------------------------+
| input[1] | -> | What `input[1]` points to |
+----------+ +---------------------------+

内容,即 input[0] 仍然与重新分配之前相同。唯一改变的是实际的 input 指针。

关于c - 如何重新分配内部和外部数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com