1

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;
}
1
  • You also need to allocate memory for what the child*s point to. Commented Apr 15, 2013 at 19:13

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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.