2014-10-18 130 views
0

我不明白爲什麼這個litle代碼不起作用!我從C struct and malloc problem (C)得到它(選定的答案),我想知道爲什麼它不適合我。malloc結構C

有什麼想法嗎?

#include <stdio.h> 
#include <stdlib.h> 

typedef struct node { 
    int value; 
    struct node *leftChild; 
    struct node *rightChild; 
} node; 

typedef struct tree { 
    int numNodes; 
    struct node** nodes; 
} tree; 

tree *initTree() { 
    /* in C code (not C++), don't have to cast malloc's return pointer, it's implicitly converted from void* */ 
    tree* atree = malloc(sizeof(tree)); /* different names for variables */ 
    node* anode = malloc(sizeof(node)); 
    atree->nodes[0] = anode; // <-------- SEG FAULT HERE ! 
    return atree; 
} 

int main() { 
    tree* mytree = initTree(); 
    return 0; 
} 
+3

atree-> nodes'指向未分配。 – BLUEPIXY 2014-10-18 23:38:16

+0

right thx尋求你的幫助 – zeomega 2014-10-18 23:42:15

回答

2

隨着以

tree* atree = malloc(sizeof(tree)); 

呼叫已分配的內存爲tree對象,所以對於一個struct node** nodes指針(因爲它是一個結構成員),但它並不指向有效記憶呢。您還必須爲它應該指向的nodes分配一個內存。例如:

atree->nodes = malloc(atree->numNodes*(sizeof (node*)));