如何使用包含数组的结构进行malloc/realloc? [英] How should I malloc/realloc with a struct that includes an array?

查看:87
本文介绍了如何使用包含数组的结构进行malloc/realloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对c很陌生,所以如果我的步骤不对,请告诉我.假设我有以下内容:

I'm pretty new to c, so if my steps are wrong, please let me know. Let's say that I have something like the following:

struct graphNode{
    int val;
    graphNode* parent;
    int succSize;
    int succMaxSize;
    graphNode* succ[1];
};

我将使用以下内容创建一个新节点:

I will create a new node with:

graphNode *n;
n = malloc(sizeof(struct graphNode));
assert(n);
n->val = 1;
n->parent = NULL;
n->succSize = 0;
n->succMaxSize = 1;

然后,如果我想向节点添加后继者

Then, if I want to add a successor to the node

if (n->succSize == n->succMaxSize){
    n->succ = realloc(n->succ, sizeof(graphNode*) * n->succMaxSize * 2);
    n->succMaxSize *= 2;
} 
n->succ[succSize] = n2; //n2 is of type graphNode*
succSize++;

这是正确的吗?我是否还需要为该结构重新分配,或者数组的重新分配是否足够?我需要为初始数组使用malloc吗?初始数组大小是否应该包含在我对n的malloc调用中?

Is this correct? Do I need to realloc for the struct as well or is realloc of the array enough? Do I need to malloc for the initial array? Should the initial array size be included in my malloc call for n?

推荐答案

在C中定义可伸缩"数组成员的通常方法是指定大小0或完全不指定大小,例如:

The usual way to define a "stretchy" array member in C is to either specify a size of 0 or no size at all, e.g.:

struct foo {
    int stuff;
    bar theBars[]; // or theBars[0]
};

使用此定义,sizeof(struct foo)将在末尾包含除数组以外的所有元素,并且您可以通过说出malloc(sizeof(struct foo) + numberOfBars * sizeof(bar))来分配正确的大小.

With this definition, sizeof(struct foo) will include all the elements other than the array at the end, and you can allocate the right size by saying malloc(sizeof(struct foo) + numberOfBars * sizeof(bar)).

如果需要重新分配它以更改bar元素的数量,则将使用相同的公式(但使用新的numberOfBars).

If you need to reallocate it to change the number of bar elements, then you'll use the same formula (but with a new numberOfBars).

要清楚,不能仅realloc结构的一部分.您必须realloc整个过程.

To be clear, you can't just realloc part of a struct. You have to realloc the whole thing.

这篇关于如何使用包含数组的结构进行malloc/realloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆