繁体   English   中英

指向struct的指针,指针指向结构的指针数组。 C中的动态内存

[英]Pointer to struct with pointer to array of pointers to structs. Dynamic memory in C

我在使用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];

在该行之后,如果我调试并设置断点,则系统节点指向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。

你写了

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

你应该写的

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

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

node* nodes = NULL; 

然后将节点分配给此行上的System->节点:

theSystem->nodes = nodes; 

由于您永远不会更改其间的节点值,因此系统 - >节点也将为NULL。

您确定以下行是正确的:

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

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

暂无
暂无

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

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