1. 程式人生 > >C語言複習 -- 結構體指標與自增運算子

C語言複習 -- 結構體指標與自增運算子

測試程式碼:

#include <stdio.h>
#include <stdlib.h>

int main() {

 struct student {
  char *name;
  int score;
 };

 struct student st = {"Brian", 97};
 struct student *ptr = &st;

 printf("ptr->name = %s\n", ptr->name);
 printf("*ptr->name = %c\n", *ptr->name);
 printf("*ptr->name++ = %c\n", *ptr->name++);
 printf("*ptr->name = %c\n", *ptr->name);
 printf("ptr->score = %d\n", ptr->score);
 printf("ptr->score++ = %d\n", ptr->score++);
 printf("ptr->score = %d\n", ptr->score);

 return 0;
}

=== 執行結果:

ptr->name = Brian
*ptr->name = B
*ptr->name++ = B
*ptr->name = r
ptr->score = 97
ptr->score++ = 97
ptr->score = 98

=== 分析:

1. ptr->name,這個不說了。

2. *ptr->name,因為->的優先順序高於*,所以相當於: *(ptr->name)。即指標首地址的那個字元。

3. *ptr->name++,由於*和++的優先順序相同,而且結合性是由右至左,所以相當於: *((ptr->name)++),即獲取首地址字元後,將name指標右移一位。(當前列印還是首地址的值)

4. *ptr->name,此處為驗證上一步的指標位置。