我在C中有一个作业,我在访问我的结构中的不同成员时遇到了问题(某些级别很深)。我理解基本原则,但我有点失去它。我有3个结构,顶部的一个包含第二个数组,而第二个包含第三个数组。我目前的问题是使用malloc正确的方法。这是我的一些代码。我会很感激任何信息或提示,因为我还有很长的路要走,因为你可以看到结构有点复杂。
.h文件
typedef struct user {
char* userID;
int wallet;
bitCoinList userBC; //Also a list
senderTransList userSendList; //Yes it has lists too..
receiverTransList userReceiveList;
}user;
typedef struct bucket {
struct bucket* next;
user** users;
}bucket;
typedef struct hashtable {
unsigned int hashSize;
unsigned int bucketSize;
bucket** buckets;
}hashtable;
这是我创建和初始化哈希表的函数。当我尝试使用HT->buckets->users
访问用户时遇到错误(请求成员用户不是结构或联合)
.c文件
// Creation and Initialization of HashTable
hashtable* createInit(unsigned int HTSize,unsigned int buckSize){
hashtable* HT = (hashtable*)malloc(sizeof(hashtable));
if(HT==NULL) {
printf("Error in hashtable memory allocation... \n");
return NULL;
}
HT->hashSize=HTSize;
HT->bucketSize=buckSize;
HT->buckets = malloc(HTSize * sizeof(HT->buckets));
if(HT->buckets==NULL) {
printf("Error in Buckets memory allocation... \n");
return NULL;
}
HT->buckets->users = malloc(buckSize * sizeof(HT->buckets->users));
if(HT->buckets->users==NULL) {
printf("Error in Users memory allocation... \n");
return NULL;
}
for(int i=0; i <HTSize; i++){
HT->buckets[i] = malloc(sizeof(bucket));
HT->buckets[i]->next = NULL;
if(HT->buckets[i]==NULL) {
printf("Error in Bucket %d memory allocation... \n",i);
return NULL;
}
for(int j=0; j <buckSize; j++){
HT->buckets[i]->users[j] = malloc(sizeof(user));
if(HT->buckets[i]==NULL) {
printf("Error in User %d memory allocation... \n",i);
return NULL;
}
}
}
return HT;
}
因为存储桶是指针类型的指针,您需要:
(*(HT-> buckets)) ->users = ....
要么
HT-> buckets[0] ->users = .... // or any other index depending of the program logic
或(对于第n个指针)
(*(HT-> buckets + n)) ->users = ....
要么
HT-> buckets[n] ->users = .... // or any other index depending of the program logic
至少有一个问题:错误的大小分配。
分配给HT->buckets
指向的数据的大小,而不是指针的大小。
避免错误。以下成语易于编码,审查和维护。
ptr = malloc(sizeof *ptr * n);
// HT->buckets = malloc(HTSize * sizeof(HT->buckets));
HT->buckets = malloc(HTSize * sizeof *(HT->buckets));
// HT->buckets->users = malloc(buckSize * sizeof(HT->buckets->users));
HT->buckets->users = malloc(buckSize * sizeof *(HT->buckets->users));
// HT->buckets[i] = malloc(sizeof(bucket));
HT->buckets[i] = malloc(sizeof *(HT->buckets[i]));
// HT->buckets[i]->users[j] = malloc(sizeof(user));
HT->buckets[i]->users[j] = malloc(sizeof *(HT->buckets[i]->users[j]));