Con trỏ và struct trong C

Mọi người cho em hỏi tại sao mà cái nhập thứ 2 trong đoạn code dưới phải có &(ptr+i) mới đúng ạ?

#include <stdio.h>
#include <stdlib.h>
struct person {
   int age;
   float weight;
   char name[30];
};
int main()
{
   struct person *ptr;
   int i, n;
   printf("Enter the number of persons: ");
   scanf("%d", &n);
   // allocating memory for n numbers of struct person
   ptr = (struct person*) malloc(n * sizeof(struct person));
   for(i = 0; i < n; ++i)
   {
       printf("Enter first name and age respectively: ");
       // To access members of 1st struct person,
       // ptr->name and ptr->age is used
       // To access members of 2nd struct person,
       // (ptr+1)->name and (ptr+1)->age is used
       scanf("%s %d", (ptr+i)->name, &(ptr+i)->age);
   }
   printf("Displaying Information:\n");
   for(i = 0; i < n; ++i)
       printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age);
   return 0;
}

Lấy vị trí ô nhớ của biến age. Lúc này cũng giống như nhập số &n như lần nhập 1 thôi.
Theo ưu tiên toán tử thì & dùng cho age chứ không phải cho (ptr+i). Đầy đủ ngoặc cho dễ hiểu là: &((ptr+i)->age).

1 Like

namechar* rồi.

2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?