繁体   English   中英

malloc结构C

[英]malloc structure C

我不明白为什么这个小代码不起作用! 我从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;
}

致电给

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

您已经为tree对象分配了内存,因此为struct node** nodes指针(因为它是结构成员)分配了内存,但是它尚未指向有效内存。 您还必须为应该指向的nodes分配一个内存。 例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM