【发布时间】: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,一切正常。但我希望它能够动态增加数组大小。
最好的问候 瓦贾哈特
【问题讨论】: