I am having trouble with some code in C accessing the contents of this chain of pointers:
I have these structs:
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;
Ok. Now I initialize everything like this:
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;
And now, I want to set this:
theSystem->nodes[2].thing = &theSystem->things[1];
After that line, if I debug and set a breakpoint theSystem nodes points to 0x0
Where am I going wrong?
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...
}
I can do this:
theSystem->nodes[2].thing->hash = 123;
And debugging shows the correct value for hash, and thing, but not for nodes. it points to 0x0.
You wrote
node* nodes = NULL;
tree = calloc(10, sizeof(node));
You should have written
node* nodes = NULL;
nodes = calloc(10, sizeof(node));
You initialize nodes to NULL on this line:
node* nodes = NULL;
Then you assign nodes to theSystem->nodes on this line:
theSystem->nodes = nodes;
Since you never change the value of nodes in between, theSystem->nodes will also be NULL.
Are you sure the following line is correct:
tree = calloc(10, sizeof(node));
Shouldn't you assign this to nodes instead?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.