2011-12-05 47 views
0

我有以下結構:我如何分配一個結構的內存?

struct Node{ 
    int *VC; 
    Node *Next; 
}; 

我的目標是創建一個指向int

指針鏈表我的問題是如何爲Node分配內存。 即

int* ptr = (int *) malloc(sizeof(int)*10); 
//code to allocate memory for a new Node n 
n->VC = ptr; 
n->Next = null; 

再後來i可以做到:

int *_ptr= (int *) malloc(sizeof(int)*10); 
//code to allocate memory for a new Node c 
c->VC= _ptr; 
c->Next = null; 

n->Next = c; 

回答

3
Node *c = malloc(sizeof(*c)); 

+0

是一樣的做: 節點* C =的malloc(的sizeof(結構節點)); – scatman

+0

@scatman它更好(想想如果你稍後改變'c'的類型會發生什麼)。 – cnicutar

+0

@Oli:永遠不要忘記結構填充。你可能會浪費一些記憶。 –

5

分配用於struct存儲器是相同的用於int(在C)分配內存。只需使用sizeof得到結構的大小:

struct Node *n = malloc(sizeof(struct Node));