我在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;
}
答案 0 :(得分:1)
因为存储桶是指向指针类型的指针,所以您需要:
(*(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
答案 1 :(得分:0)
至少一个问题:大小分配错误。
分配给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]));