views:

159

answers:

1

I am trying to pass a structure array pointer and a pointer to a structure array pointer into a function and then have it modified rather than using a return.

This example code is indeed pointless, its just a learning example for me.

Basically I want to create array[0]...array[1]..array[2] and so on and have a pointer that points to these while using a different index...such as array_ref[2] points to array[0] and array_ref[3] points to array[1].

The code below compiles, but immediately crashes. Any suggestions?

typedef struct unit_class_struct {
    char *name;
    char *last_name;
} person;




int setName(person * array, person ***array_ref) {
   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;

   array = calloc (5, sizeof(person));
   array_r = calloc (5, sizeof(person));

   setName(array,&array_r);

    printf("First name is %s %s\n", array_r[2]->name, array_r[2]->last_name);
    printf("Second name is %s %s\n", array_r[3]->name, array_r[3]->last_name);

    return 0;
}
+2  A: 

You are allocating an array of structures but declaring an array of pointers.

Calloc() and malloc() return a void * object that can be assigned to everything. So, even with -Wall your program will compile with no warnings.

However, when it runs, it tries to deal with what you said was an array of pointers, in fact, an array of pointers to pointers to pointers. None of these pointers are ever created. All you start with are one-level pointers to an array of objects. Depending on what you really want, you may need something more like...

    array_ref[2] = &array[0];
    array_ref[3] = &array[1];

    return 1;
}


int main()
{
    person *array, *array_r_real;
    person **array_r;

    array = calloc(5, sizeof(person));
    array_r_real = calloc(5, sizeof(person));
    array_r = calloc(5, sizeof(struct unit_class_struct *));
    int i;
    for (i = 0; i < 5; ++i)
        array_r[i] = &array_r_real[i];

    setName(array, array_r);
DigitalRoss
Actually, if it was my program, I might have used: `array_r[i] = array_r_real + i;`
DigitalRoss