結構體
1、結構體變數的初始化
例:
#include "StdAfx.h" #include<stdio.h> void main() { struct { int num; char *name; char sex; float score; }boy1,boy2={102,"Jane",'M',98.5}; boy1=boy2; printf("number=%d\nname=%s\nscore=%f\n",boy1.num,boy1.name,boy1.score); printf("number=%d\nname=%s\nscore=%f\n",boy2.num,boy2.name,boy2.score); }
2、結構體陣列
一個結構體變數中可以存放一組資料(如一個學生的學號,姓名,成績等資料)。若有10個學生的資料需要參加運算,顯然應用陣列,這就是結構體陣列。結構體陣列與數值型陣列不同之處在於每一個數組元素都是一個結構體型別的資料,它們都分別包括各個成員項。
例:
#include "StdAfx.h" #include<stdio.h> #include<stdlib.h> #define NUM 3 struct person { char name[20]; char phone[10]; }; void main() { struct person man[NUM]; int i; for(i=0;i<NUM;i++) { printf("input name:\n"); gets(man[i].name); printf("input phone:\n"); gets(man[i].phone); } printf("\tname\t\t\tphone\n\n\n"); for(i=0;i<NUM;i++) { printf("%10s\t\t%10s\n",man[i].name,man[i].phone); } system("pause"); }
定義結構體陣列
與其他型別陣列一樣,對結構體陣列也可以初始化。
例:
struct student { int num; char name[20]; char sex; int age; float score; char addr[30]; }stu[2] = { {101,"LILIN","m",18,97.5,"beijing"}, {102,"zhang","f",17,99,"shanghai"} };
也可用如下形式:
struct student { int num; char name[20]; char sex; int age; float score; char addr[30]; }; struct student str[2] = { {101,"LILIN","m",18,97.5,"beijing"}, {102,"zhang","f",17,99,"shanghai"} };
即先宣告結構體型別,然後定義陣列為該結構體型別,在定義陣列是初始化。
3、指向結構i資料型別的指標
一個結構體變數的指標就是該結構體變數所佔據的記憶體段的起始地址。
可以設一個指標變數,用來指向一個結構體變數,此時該指標變數的值是結構體變數的起始地址。
指標變數也可以用來指向結構體陣列中的元素。
說明的一般形式:struct 結構名 *結構指標變數名
例:已說明一個指向stu的指標變數pstu,struct stu*pstu;也可在定義stu結構的同時說明pstu。
與之前討論的各類指標變數相同,結構指標變數也必須先賦值,然後才能使用。
賦值是把結構變數的首地址賦予該指標變數,不能把結構名賦予該指標變數。
例:若boy是被說明為stu型別的結構變數,則:pstu=&boy是正確的,而pstu=&stu是錯誤的。
原因:結構名和結構變數是兩個不同的概念,結構名只能表示一個結構形式,系統並不能為其分配記憶體空間,只有當某個變數被說明為這種型別的結構時,才能對變數分配記憶體空間。
呼叫的一般形式為:(*結構指標變數).成員名或為:結構指標變數→成員名
例:
#include "StdAfx.h" #include<stdio.h> struct stu { int num; char *name; char sex; float score; }boy1={102,"kun",'m',98.5}; void main() { struct stu *pstu; pstu=&boy1; printf("number=%d\nname=%s\nsex=%c\nscore=%f\n",boy1.num,boy1.name,boy1.sex,boy1.score); printf("number=%d\nname=%s\nsex=%c\nscore=%f\n",(*pstu).num,(*pstu).name,(*pstu).sex,(*pstu).score); }