Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc a pointer to a pointer to a structure array by reference

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;
}
like image 584
ZPS Avatar asked Dec 29 '22 09:12

ZPS


1 Answers

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.

like image 118
Pavel Minaev Avatar answered Jan 01 '23 15:01

Pavel Minaev