gpt4 book ai didi

c - 结构体内部的 int 数组

转载 作者:行者123 更新时间:2023-11-30 17:50:44 24 4
gpt4 key购买 nike

我正在尝试实现这一点...一个包含结构数组的单个容器,并且每个结构内部都是一个表示整数的 int 数组,如下所示... 12,345 将位于 int 数组内[5 ]={1,2,3,4,5}

有什么方法可以实现这一点。这个实现的主要问题是我迷失了所有指向各处的指针,并且开始出现垃圾数据和段错误。哦,是的,顺便说一句,一切都是动态的。好吧,我猜几乎所有的事情,如果你有一个结构容器,里面有一个结构,如果容器是 malloc 的,那么它里面的结构也会自动 malloc 的,所以我的猜测是

容器->struct.array

不确定???

最佳答案

您需要自己编写结构体和容器的 malloc 和 free 函数,并在每次需要容器或释放其空间时调用它们,例如:

struct outside{
struct inside *in;
};


struct inside{
int *array;
};

struct outside *malloc_outside(size_t n) {
int i;
struct outside *o;
o = (struct outside *)malloc(n*sizeof(struct outside));
for(i=0;i<n;i++) {
o->in = malloc(sizeof(struct inside));
o->in->array = NULL;
}
return o;
}


void free_outside(struct outside *out) {
free(out->in->array);
free(out->in);
free(out);
return;
}

和 malloc() 数组的空间作为您在 malloc_outside() 之后需要的空间

在 C++ 中通过构造函数和析构函数更容易实现。

关于c - 结构体内部的 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17077630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com