gpt4 book ai didi

c - 在 struct - C 中初始化数组?

转载 作者:太空宇宙 更新时间:2023-11-04 07:41:04 25 4
gpt4 key购买 nike

似乎有内存分配问题并认为这是因为在我的结构中,有一个指向另一个结构的数组的指针。但是,我没有初始化这个数组,也不确定如何:

typedef struct listitem {
struct listitem *next;
Entry *entry;
} ListItem;

typedef struct list {
ListItem *table[100];
} List;

List *initialize(void)
{
List *tmp;

if ((tmp = (List *)malloc(sizeof(List))) == NULL)
return NULL;
return tmp;
}

希望这是有道理的,你可以帮助!

最佳答案

您将需要再次调用 malloc。

typedef struct listitem {
struct listitem *next;
Entry *entry;
} ListItem;

typedef struct list {
ListItem *table[100];
} List;

List *initialize(void)
{
List *tmp;

if (!(tmp = (List *)malloc(sizeof(List))))
return NULL;
for(int i = 0; i < 100; i++) {
tmp->table[i] = (ListItem*)malloc(sizeof(ListItem));
}
return tmp;
}

关于c - 在 struct - C 中初始化数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4019483/

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