結構體的賦值和初始化與取出結構體變量中的成員


 1  /* 結構體的賦值和初始化 */
 2 
 3 # include <stdio.h>
 4 
 5  struct Student 
 6 {
 7      int age;
 8      float score;
 9      char sex;
10 };
11 
12  int main( void)
13 {
14      struct Student st = {  8066.6' F '}; // 定義同時就賦值
15       struct Student st2; // 下一行不能寫一句類似於st2 = { 10, 88, 'M'};的語句,除非定義時就賦值。
16      st2.age =  10;
17     st2.score =  88;
18     st2.sex =  ' M ';
19 
20     printf( " %d , %f, %c\n ", st.age, st.score, st.sex);
21     printf( " %d , %f, %c\n ", st2.age, st2.score, st2.sex);
22 
23      return  0;
24 }
25  /*
26  在Vc++6.0中顯示的結果是:
27  =========================================
28  80 , 66.599998, F
29  10 , 88.000000, M
30  =========================================
31  */

 

  1 /*

 2  如何取出結構體變量中的每一個成員
 3  */
 4 # include <stdio.h>
 5 
 6  struct Student 
 7 {
 8      int age;
 9      float score;
10      char sex;
11 };
12 
13  int main( void)
14 {
15      struct Student st = {  8066.6F' F '};
16     printf( " age = %d\n ",st.age);
17 
18 
19      struct Student * pst = &st; // &st不能改成st
20      pst->age =  88;   // 第二種方式。。。pst->age在計算機內部,會被轉化成(*pst).age 這是一種硬性規定
21                       // 所以pst->age等價於(*pst).age ,也等價於st.age
22      printf( " age = %d\n ",st.age);
23 
24 
25     st.age =  10;   // 第一種方式
26      printf( " age = %d, score = %f\n ",st.age, pst ->score); // st.age可寫成pst ->age, pst ->score也可寫成st.score.
27 
28      return  0;
29 }
30  /*
31  在Vc++6.0中顯示的結果是:
32  ==============================================================
33  age = 80
34  age = 88
35  age = 10, score = 66.599998
36  ==============================================================
37  */

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM