Billy
Billy

Reputation: 43

How to use an array of pointers inside a structure correctly

I have two structures parent and child as you can see in my code below. The parent structure has an array of pointers of type child. I get a segmetation error when the the program enters the for loop. Is there any thing wrong in my code? The reason why I don't want to use square brackets is that I have a function that takes a pointer parameter of type child and I want to pass every child pointer to that function without the need to use &.

Any help would be appreciated Thank you

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
   int id;
} child;

typedef struct {
   child** c;
} parent;

int main(int argc, char **argv) {
    int number_of_children = 5;

parent* p = (parent*)malloc(sizeof(parent));

p -> c = (child **) malloc(number_of_children * sizeof(child*));

int i;
for(i=0; i<number_of_children; i++)
    p -> c[i] -> id = i;
}

Upvotes: 1

Views: 2249

Answers (2)

Lundin
Lundin

Reputation: 213693

Not tested, but it should be something along these lines:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
   int id;
} child;

typedef struct {
   child** c;
} parent;

int main(int argc, char **argv) {
    const int number_of_children = 5;

    parent* p = malloc(sizeof(parent));
    if(p == NULL) halt_and_catch_fire();

    p->c = malloc(number_of_children * sizeof(child*));
    if(p->c == NULL) halt_and_catch_fire();    

    for(int i=0; i<number_of_children; i++)
    {
        p->c[i] = malloc(sizeof(child));
        if(p->c[i] == NULL) halt_and_catch_fire();

        p->c[i]->id = i;
    }

    // free() *everything* allocated
}

As we can see, you are trying to allocate a segmented pointer-to-pointer thing, which there is no obvious need for, since you do not allocate more than one of the inner-most objects. If you are trying to create a multi-dimensional array, you shouldn't make a segmented mess, do like this instead.

Upvotes: 1

zakinster
zakinster

Reputation: 10688

You are correctly allocating the children pointer table but you're not allocating any child.

int i
for(i = 0; i < number_of_children; ++i) {
    p->c[i] = (child *) malloc(sizeof(child));
    p -> c[i] -> id = i
}

Upvotes: 5

Related Questions