graceshirts graceshirts - 1 year ago 73
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?


#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]));


return 0;





Answer Source

people is a pointer to Person. E1[E2] is an array subscript operation, that is equal to *((E1) + (E2)) ( 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 */
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download