在c进行结构结构指针数组灵活的初始化 [英] initialization of flexible array of struct pointers in a struct in c
问题描述
我学习哈希表的数据结构,我想和指针的灵活长度阵列结构体的链接(链接列表件)散列表,这样,哈希表初始化将设置阵列是一个长度输入到初始化函数。
I'm learning hashtable data structures and I want to make a hashtable with a flexible length array of pointers to struct Link (linked list pieces), so that hashtable initialization will set the array to be a length input into the initialization function.
起初我得到的错误柔性阵列不是结构的终结。当其在端(如图所示)的程序崩溃(但它仍然编译)。这是我的code:
At first I was getting the error "flexible array not at the end of struct". When its at the end (as shown) the program crashes (but it still compiles). This is my code:
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;
}
}
}
它的工作原理,如果我数组常量,输入相同的值设置到初始化函数:
It works if I set the array to a constant and input the same value into the init function:
#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;
}
}
}
第二code座完美的作品。任何见解将大大AP preciated。谢谢你的时间。
克里斯
The second code block works perfectly. Any insights would be greatly appreciated. Thanks for your time. Chris
推荐答案
您应该分配内存
HashTable *newHT = malloc(sizeof *newHT + size * sizeof newHT->Table[0]);
这篇关于在c进行结构结构指针数组灵活的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!