有一个数组:
type **a;
a[0][data_0]
a[1][data_1]
a[2][data_2]
a[n][data_n]
通过执行以下操作扩展此类数组时:
a
上的realloc()
到sizeof(type*) * (n + 1)
。malloc()
(*a[n])
适合data_n
,其中data_n
的大小可变.
a
的 realloc()
是否存在问题?
正如a[2]
中那样,即使a
在内存中移动,或者该链接可能丢失,它也始终指向data_2
?
据我了解,我最终在内存中得到了这样的结果:
Address Address
a[0] => 0x###131, (*a[0]) => 0x####784
a[1] => 0x###135, (*a[1]) => 0x####793
a[2] => 0x###139, (*a[2]) => 0x####814
在realloc()
之后我可能会得到类似的结果:
Address Address
a[0] => 0x###216, (*a[0]) => 0x####784
a[1] => 0x###21a, (*a[1]) => 0x####793
a[2] => 0x###21e, (*a[2]) => 0x####814
a[n] => 0x###zzz, (*a[n]) => 0x####yyy
这是正确的吗? data_n 段被单独保留,或者它们也可以被移动吗?
最佳答案
Is this correct? The data_n segments are left alone, or could they also get moved?
是的,a[i]
的值,对于0 <= i < n
被复制到新位置,因此指针指向相同的 data_i
并且这些不会被移动。
Could there be some issue with
realloc()
ofa
?
当然,一个realloc
总是会失败并返回 NULL
,所以你永远不应该这样做
a = realloc(a, new_size);
但是使用临时变量来存储realloc
的返回值.
关于c - 重新分配数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12801105/