0

I am having trouble trying to dereference a double pointer to an array of structs.

The struct is defined:

struct node_list_t {
     struct node_t **node_ptr;
};

I have done the following to allocate memory and initialize values:

struct node_t *nodeArray;
struct node_list_t *mainList = (struct node_list_t*)malloc(sizeof(struct node_list_t));

nodeArray =(struct node_t*)malloc(10 * sizeof(struct node_t));
for (i=0;i<size;i++) {
    nodeArray[i].mass = i;
}

mainList->node_ptr = &nodeArray;

Since we are being required to use a double pointer I am trying the following unsuccessfully to dereference as such:

printf("%f\n",mainList->node_ptr[i]->mass);

We are forced to keep node_ptr as a double pointer, so I cannot change that. How would I dereference this? Thanks.

Ajay Brahmakshatriya
  • 8,993
  • 3
  • 26
  • 49
Austin
  • 347
  • 7
  • 21

1 Answers1

2

Well, that would be

printf("%f\n",(*mainList->node_ptr)[i].mass);

Why? mainList->node_ptr is double pointer to struct node_t.

*mainList->node_ptr dereference the double pointer and you get a single pointer to struct node_t: the pointer returned from the second malloc.

So (*mainList->node_ptr)[i].mass is equivalent to

struct node_t *nodes = *mainList->node_ptr;
// nodes[0] is the first node, nodes[1] the second, etc.
nodes[i].mass;

edit

When you have trouble finding the correct dereference in one line, do it step by step like in my example above. Then it is much easier to rewrite it in one line.

edit 2

Since the OP removed the code from the question, this answer makes no sense without it, this was the original code:

struct node_list_t {
     struct node_t **node_ptr;
};

I have done the following to allocate memory and initialize values:

struct node_t *nodeArray;
struct node_list_t *mainList = (struct node_list_t*)malloc(sizeof(struct node_list_t));

nodeArray =(struct node_t*)malloc(10 * sizeof(struct node_t));
for (i=0;i<size;i++) {
    nodeArray[i].mass = i;
}

mainList->node_ptr = &nodeArray;
Pablo
  • 13,271
  • 4
  • 39
  • 59