【问题标题】:How to update and array of pointers to elements of an array after realloc moves the memory location of that array在 realloc 移动该数组的内存位置后如何更新和指向数组元素的指针数组
【发布时间】:2012-10-17 01:38:48
【问题描述】:

我是初学者,在动态内存分配方面遇到了困难。如果有人能帮我解决这个问题,我将不胜感激。

我使用 malloc 为数组节点分配一些内存:

struct nodeT {
int id;
nodeT *parent, *T1, *T2;
};

struct nodeT* T;
T =  (struct nodeT*) malloc( 256*sizeof(struct nodeT) );

Then in order to reference T, I use a an array of pointers to T, call it Tptr:

struct nodeT** Tptr;
Tptr = (struct nodeT**) malloc( 256*sizeof(struct nodeT*) );

在我的代码中,我将数据填充到 T 中,然后迭代设置 *Tptr = T,如下所示:

nodeT* s = &T[ 1*21 ];
s->id=23;
s->T1=...
s->T2=...
s->parent=...

然后

sptr = &Tptr[ 1*21 ];
*sptr=s;
and it works fine.

但有时,当我调用 realloc 来增加 T 的大小,然后我检查 *sptr 时,它不再有效,我在运行时遇到分段错误。我认为 realloc 有时可能会将整个内存块移动到新位置,而 *sptr 一直指向旧位置。

知道如何在每次 realloc 之后更新所有 Tptr。

如果我从一开始就使用大尺寸的 T 并为 T 禁用 realloc,一切正常。但我希望它能够动态增加数组大小。

最好的问候 瓦贾哈特

【问题讨论】:

    标签: pointers malloc realloc


    【解决方案1】:

    您对 malloc 的调用设置了 T。 当您调用 re-alloc 时,您不能假设 T 将在同一个地方 由于调用后设置了Tptr Tptr = T

    T =  (struct nodeT*) malloc( 256*sizeof(struct nodeT) );
    

    您的指针数组 TPtr 需要在 T 上的每个 realloc 之后重新填充。 如果您不想自己执行此操作,请使用向量而不是数组和 realloc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 1970-01-01
      相关资源
      最近更新 更多