typedef struct unit_class_struct {
char *name;
} person;
person * setName() {
person * array;
array = malloc (2 * sizeof(person));
array->name = strdup("Robert");
array++;
array->name = strdup("Jose");
return array;
}
int main()
{
person *array;
array = setName();
printf("First name is %s\n", array[0].name);
printf("Second name is %s\n", array[1].name);
return 0;
}
In this example, array[0].name returns Jose, not Robert as I expected, and array[1].name is empty.
However if I use
person * setName() {
person * array;
person * array_switch;
array = malloc (2 * sizeof(person));
array_switch = array;
array_switch->name = strdup("Robert");
array_switch++;
array_switch->name = strdup("Jose");
return array;
}
It works as expected. array.name[0] returns Robert and array.name[1] returns Jose.
Why does it require a second pointer for this example to work? Can I do it without using a second pointer AND still use pointer arithmetic?
I already know this is another way to do it as well:
person * setName() {
person * array;
array = malloc (2 * sizeof(person));
array[0].name = strdup("Robert");
array[1].name = strdup("Jose");
return array;
}