gpt4 book ai didi

c - 在c中的结构中初始化灵活的结构指针数组

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

我正在学习哈希表数据结构,我想制作一个哈希表,其中包含指向 struct Link(链表片段)的灵活长度的指针数组,以便哈希表初始化会将数组设置为初始化函数的长度输入.

起初我收到错误“灵活数组不在结构的末尾”。当它结束时(如图所示)程序崩溃(但它仍然可以编译)。这是我的代码:

typedef struct Link{
int key;
char *name;
struct Link *next;
} Link;

typedef struct HashTable{
int numberOfEntries;
int numberOfBuckets;
Link *Table[];
} HashTable;

HashTable *hashtableInit(int size){
HashTable *newHT = malloc(sizeof(HashTable));
if (newHT != NULL){
newHT->numberOfEntries = 0;
newHT->numberOfBuckets = size;
for (int i = 0; i < newHT->numberOfBuckets; i += 1){
newHT->Table[i] = NULL;
}
return newHT;
} else {
printf("Error in memory allocation.\n");
fflush(stdout);
return NULL;
}
}
}

如果我将数组设置为常量并将相同的值输入到 init 函数中,它会起作用:

#define SIZE 11

typedef struct Link{
int key;
char *name;
struct Link *next;
} Link;

typedef struct HashTable{
Link *Table[SIZE];
int numberOfEntries;
int numberOfBuckets;
} HashTable;

HashTable *hashtableInit(int size){ // works if SIZE is passed into function as size parameter
HashTable *newHT = malloc(sizeof(HashTable));
if (newHT != NULL){
newHT->numberOfEntries = 0;
newHT->numberOfBuckets = size;
for (int i = 0; i < newHT->numberOfBuckets; i += 1){
newHT->Table[i] = NULL;
}
return newHT;
} else {
printf("Error in memory allocation.\n");
fflush(stdout);
return NULL;
}
}
}

第二个代码块完美运行。任何见解将不胜感激。谢谢你的时间。克里斯

最佳答案

你应该分配内存

HashTable *newHT = malloc(sizeof *newHT + size * sizeof newHT->Table[0]);

关于c - 在c中的结构中初始化灵活的结构指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19748891/

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