The code below compiles, but immediately crashes for reasons obvious to others, but not to me. I can't seem to get it right, can anyone tell me how to fix this.
*array_ref[2] = array[0];
*array_ref[3] = array[1];
It crashes on that part everytime.
typedef struct test {
char *name;
char *last_name;
} person;
int setName(person ** array, person ***array_ref) {
*array = malloc (5 * sizeof(person));
*array_ref= malloc(5 * sizeof(person*));
array[0]->name = strdup("Bob");
array[1]->name = strdup("Joseph");
array[0]->last_name = strdup("Robert");
array[1]->last_name = strdup("Clark");
*array_ref[2] = array[0];
*array_ref[3] = array[1];
return 1;
}
int main()
{
person *array;
person **array_r;
setName(&array,&array_r);
printf("First name is %s %s\n", array[0].name, array[0].last_name);
printf("Second name is %s %s\n", array_r[3]->name, array_r[3]->last_name);
while(1) {}
return 0;
}
Operator []
has higher precedence than unary operator*
. Hence, this:
*array_ref[2] = array[0];
*array_ref[3] = array[1];
actually means:
*(array_ref[2]) = array[0];
*(array_ref[3]) = array[1];
Types are correct here, which is why it compiles. But from your code it's clear that your intent actually was:
(*array_ref)[2] = array[0];
(*array_ref)[3] = array[1];
So just use parentheses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With