你不必重新分配“内部数组”。您分配的内存的内容是指针,并且当您重新分配input
时,则只能重新分配input
指针,而不是其中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
指针。
所以你的意思是我可以做这样的事情“input =(char **)realloc(input,previousSize + 1)” – 2013-02-22 20:08:38
@NickStov是的。 – 2013-02-22 20:12:01
@NickStov对于关键系统,如果realloc()失败,您可能需要考虑原始“输入”指针会发生什么情况。但是,为了您在这里的具体目的,我认为您对您很重要。另外,由于realloc()的行为与malloc()类似,所以如果你传递一个初始的NULL值,你不需要'malloc()'作为初始'input'值,所以只要确保'input'是NULL当这整件事开始时。 (和这个答案+1,我爱ascii艺术= P)。 – WhozCraig 2013-02-22 20:16:19