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 = { 80, 66.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 = { 80, 66.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 */