c - 重新分配数组索引

标签 c arrays malloc realloc

有一个数组:

type **a;

a[0][data_0]
a[1][data_1]
a[2][data_2]
a[n][data_n]

通过执行以下操作扩展此类数组时:

  1. a 上的 realloc()sizeof(type*) * (n + 1)
  2. malloc() (*a[n]) 适合 data_n,其中 data_n 的大小可变.

arealloc() 是否存在问题?

正如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() of a?

当然,一个realloc总是会失败并返回 NULL ,所以你永远不应该这样做

a = realloc(a, new_size);

但是使用临时变量来存储realloc的返回值.

关于c - 重新分配数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12801105/

相关文章:

c - 为什么 bits/libc-header-start.h 文件夹包含在 stdio.h header 中

c - 除了在头文件中声明的那些之外,程序是否需要来自 .so 共享库的其他符号?

javascript - 如何编写JS函数从字符串中删除某些符号数组

c - 接收到数组的浮点指针 malloc 数组

c - 如果只使用第一个元素,我是否必须为整个结构分配内存?

C 错误 : expected `=' , `,' 、 `;' 、 `asm' 或 `__attribute__' 之前

c - C中通过指针修改函数中数组的值

arrays - 减少要在 Swift 中设置的数组

c - 为什么会出现 C malloc 断言失败?

c - 段错误(核心转储)[康威的生命游戏]