【发布时间】: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