Nic*_*tov 4 c string memory-management
所以,我得到了一个奇怪的任务.我必须将文件内容读取到数组字符串.但是,我必须像这样初始化数组(我必须将其初始化为数组大小1):
char **input = (char **)malloc(1*sizeof(char*))
Run Code Online (Sandbox Code Playgroud)
代替
char **input = (char **)malloc((sizeOfFile+1)*sizeof(char*))
Run Code Online (Sandbox Code Playgroud)
所以,我必须继续使用realloc.我的问题是,如何重新分配内部数组(字符串)以及如何重新分配外部数组(字符串数组)
您不必重新分配"内部数组".您分配的内存的内容是指针,当您重新分配时,input您只需重新分配input指针,而不是指向where的内容input.
粗略的ASCII图像,以显示它的工作原理:
首先,当您在input数组中分配单个条目时,它看起来像这样:
+----------+ +---------------------------+
input -> | input[0] | -> | What `input[0]` points to |
+----------+ +---------------------------+
Run Code Online (Sandbox Code Playgroud)
重新分配后,为第二个条目(即input = realloc(input, 2 * sizeof(char*));)
+----------+ +---------------------------+
input -> | input[0] | -> | What `input[0]` points to |
+----------+ +---------------------------+
| input[1] | -> | What `input[1]` points to |
+----------+ +---------------------------+
Run Code Online (Sandbox Code Playgroud)
内容,即input[0]仍然与重新分配之前相同.唯一改变的是实际input指针.