【问题标题】:Pointer to struct with pointer to array of pointers to structs. Dynamic memory in C指向结构的指针和指向结构的指针数组的指针。 C中的动态内存
【发布时间】:2012-07-16 01:26:30
【问题描述】:

我在 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。

【问题讨论】:

  • 你在这里编造一些东西。 theSystem->nodes[2].thing = theSystem->things[1] 行甚至无法编译。左侧是指针。右手边是一个结构。请不要编造代码。发布真实代码或至少与真实代码足够接近的内容。
  • 这正是我在这里的原因。 if (theSystem->nodes[2].thing == NULL) 是假的,但调试不是这样。
  • 不,不,不。同样,您发布的代码不会编译。它无法运行或调试。除非您使用完全未知的东西,否则任何现有的编译器都无法编译我提到的行。你用的是什么编译器?
  • 据我所知,我正在使用 gcc。
  • 好吧,我不知道 GCC 中什么样的主要故障允许编译 theSystem->nodes[2].thing = theSystem->things[1] 行,但无论如何,分配没有任何意义。您不能将 struct 分配给指针。代码简直毫无意义。你认为这个作业应该做什么?

标签: c arrays memory pointers dynamic


【解决方案1】:

你写的

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

你应该写的

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

【讨论】:

  • 我已更新代码以反映此修复,请查看。
【解决方案2】:

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

node* nodes = NULL; 

然后你将节点分配给系统->这一行的节点:

theSystem->nodes = nodes; 

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

你确定下面这行是正确的吗:

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

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

【讨论】:

  • 是的,这是错误的,但只是在这个问题上。实际代码是正确的,我已经更新了主要问题。
猜你喜欢
  • 1970-01-01
  • 2017-06-03
  • 2021-07-14
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
相关资源
最近更新 更多