0

Goal: to fill array of structs with data.

Suppose I have this:

struct mammal* myDogs = NULL;
doSomething(mammal);

Then inside doSomething I have:

void doSomething(struct mammal* doggies) {
    doggies = malloc(sizeof(struct mammal) * (10)); // I want to create 10 doggies
    doSomethingElse(doggies);
    
    printf("First doggie age is...%d\n", doggies[0].age); // Ouput OK!
}

Returning back to main function, where I had that "doSomething" call:

printf("First doggie age is...%d\n", doggies[0].age); // Segmentation fault
printf("First doggie age is...%d\n", (doggies+0)->age); // Segmentation fault

I understand how pointers work, but got confused in that simple case. Can somebody share knowledge, please? :D How to get my data from main function?

  • pointer is value copied in your function. If you'd like to edit it, you should use a pointer to that argument. `void doSomething(struct mammal ** doggies)` – Mert Can Ergün Mar 04 '22 at 10:48

0 Answers0