1

我在 C 中的某些代码访问此指针链的内容时遇到问题:

我有这些结构:

typedef struct {
    unsigned int hash;
    char string[10]; 
    void *memory;
} thing;

typedef struct {
    int num; 
    thing *thing;
} node;


typedef struct {
    int size;
    thing* things;
    node* nodes;
} t_system;

行。现在我像这样初始化所有东西:

thing* things = NULL;
things = calloc(10, sizeof(thing));

node* nodes = NULL;
nodes = calloc(10, sizeof(node));

t_system* theSystem = NULL;
theSystem = calloc(1, sizeof(t_system));

    theSystem->things = things;
    theSystem->nodes = nodes;

现在,我想设置这个:

theSystem->nodes[2].thing = &theSystem->things[1];

在该行之后,如果我调试并设置断点 theSystem 节点指向 0x0

我哪里错了?


if (theSystem->nodes[2].thing == NULL) {
    theSystem->nodes[2].thing = &theSystem->things[1]; //this is executed
}
if (theSystem->nodes[2].thing == NULL) {
    //this is not executed...
}

我可以做这个:

theSystem->nodes[2].thing->hash = 123;

调试显示哈希和事物的正确值,但不显示节点的正确值。它指向 0x0。

4

2 回答 2

2

你写了

node* nodes = NULL;
tree = calloc(10, sizeof(node));

你应该写

node* nodes = NULL;
nodes = calloc(10, sizeof(node));
于 2012-07-17T06:39:13.623 回答
1

您在此行将节点初始化为 NULL:

node* nodes = NULL; 

然后在这一行将节点分配给 System->nodes:

theSystem->nodes = nodes; 

由于您从不更改中间节点的值,因此 System->nodes 也将为 NULL。

您确定以下行是正确的:

tree = calloc(10, sizeof(node));  

你不应该把它分配给节点吗?

于 2012-07-17T06:40:07.613 回答