graceshirts graceshirts - 4 months ago 8
C Question

accessing structure's member by using pointer

I compiled the code below on gcc(x64).

Why can I access the structure items by putting dot(people[0].name) rather than '->'?

Isn't people[0] is pointing to the address of the structure and I should use people[0]->name or (*people[0]).name to access the name?

Code:

#include <stdio.h>

#define TOTAL 4

int main(void) {
typedef struct tagPerson {
char name[12];
int ID;
} Person;

#define LPPERSON Person*

Person * people = calloc(sizeof(Person), TOTAL);
strncpy(people[0].name, "Henry", 12);
strncpy(people[1].name, "Jacob", 12);

printf("sizeof(people)=%d\n", sizeof(people));
printf("people[0].name=%s\n", people[0].name);
printf("sizeof(people[0])=%d\n", sizeof(people[0]));
printf("people[1].name=%s\n", people[1].name);
printf("sizeof(people[1])=%d\n", sizeof(people[1]));

free(people);

return 0;
}


Output:

sizeof(people)=8

people[0].name=Henry
sizeof(people[0])=16

people[1].name=Jacob
sizeof(people[1])=16

Answer

people is a pointer to Person. E1[E2] is an array subscript operation, that is equal to *((E1) + (E2)) (6.5.2.1). Here E1 must be pointer to T and E2 must be of an integer type. Type of whole expression is simply T. In your case E1 is a pointer to Person, so people[0] has type of Person, and access to fields is performed via . instead of ->.

If you want to use arrow - you can do it in next way:

(people + 1)->name; /* the same as people[1].name */