2014-10-18 85 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*)));