1

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.

13

2 Answers 2

2

You wrote

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

You should have written

node* nodes = NULL;
nodes = calloc(10, sizeof(node));
Sign up to request clarification or add additional context in comments.

1 Comment

I have update the code to reflect this fix, please take a look.
1

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?

1 Comment

Yes that was wrong, but just in this question. The actual code is correct, i have updated the main question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.