I am learning C in one of my classes. In one of my labs we need to use an array of structs.
One of my lab TAs told me I should be using array like this:
typedef struct person {
int age;
char *name;
} Person;
int main() {
Person **people = (Person **)malloc(sizeof(Person *));
Person *personA = (Person *)malloc(sizeof(Person));
personA->age = 18;
personA->name = "LeBron James";
Person *personB = (Person *)malloc(sizeof(Person));
personB->age = 20;
personB->name = "Kobe Bryant";
Person *personC = (Person *)malloc(sizeof(Person));
personC->age = 21;
personC->name = "Michael Jordan";
people[0] = personA;
people[1] = personB;
people[2] = personC;
printf("Name of first person is %s \n", people[0]->name);
printf("Name of second person is %s \n", people[1]->name);
printf("Name of second person is %s \n", people[2]->name);
The result is right. But what I do not understand why the pointer to a pointer (people
) can behave like an array? (e.g people[0] = personA
)
Can somebody please explain this to me?