我有這個結構的問題,我不明白爲什麼不起作用。我創建了一個具有3個值的結構,我希望這個SIZE = 100的數組。但是我對malloc感到困惑,以及它在這種情況下是如何工作的。數組結構 - 哈希表
#define SIZE 100
typedef struct entry {
long id;
int r1;
int r2;
int r3;
};
typedef struct entry * THash; //[SIZE];
THash init()
{
int i;
THash t = malloc(SIZE*sizeof(struct entry));
for(i = 0; i<SIZE; i++){
t[i] = malloc(sizeof(struct entry));
t[i].id = -1;
t[i].r1 = -1;
t[i].r2 = -1;
t[i].r3 = -1;
}
return t;
}
你不需要兩次分配內存問更多的問題。第一個malloc就夠了。它爲所有100個結構分配內存。你可以直接在循環中使用它們。也請記住在使用後釋放內存。這通常是一個很好的做法。 –