我在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;
}发布于 2019-03-09 20:08:33
因为buckets是指向指针类型的指针,所以您需要:
(*(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这只是语法上的回答,我不分析程序逻辑
发布于 2019-03-09 23:06:37
至少有一个问题:错误的大小分配。
分配给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]));https://stackoverflow.com/questions/55077092
复制相似问题