標籤:
一、結構體
1)聲明
struct 用來聲明結構體
作用:管理多個資料資訊
struct student{ int num; //成員變數之間用;隔開 int age; char name[30]; float score;}Student;//分號不要忘記
2) 初始化
1、設定初始值使用{}
2、按照成員變數的順序賦值
3、可以不設定資訊,使用{0}
Student stu1={1,18,"luofeng",90.0}; Student stu2={2,81,"sunjude",99.9}; Student stu3={0};
4、相同結構體類型變數可以相互賦值[數組名是不可以的]
stu3 = stu1;
5、結構體變數定義以後,不能整體賦值,只能給成員變數單獨賦值
strcpy(stu2.name, "canglaoshi");
printf("%d,%d,%s,%.2f",stu1.num,stu1.age,stu1.name,stu1.score);
3)typedef 原類型名 新類型名
1、 typedef struct student Animal; //結構體重新命名
typedef float ok;int main(int argc, const char * argv[]) { ok a= 0.89; printf("%f\n",a); return 0; }
4)局部變數
1、在函數內定義,整個函數內有效
2、範圍:在{}內有效,出了{}就被釋放,不能再使用
3、不同的函數中,可以定義相同的變數,每個函數都有自己的範圍
4、在某程式碼片段中定義,只能在程式碼片段中使用,迴圈,分支
5、在函數中定義了變數,然後再程式碼片段中也定義了相同的變數[在程式碼片段中,以程式碼片段內的變數使用,在程式碼片段外,以函數內的變數使用]
5)全域變數
1、函數外定義,程式運行結束釋放
2、從全域變數定義的位置開始,下面的程式中都能使用全域變數
3、全域變數和局部變數可以重新命名
4、設定初始值使用{}, 可以不設定資訊,使用{0}
5、按照成員變數的順序賦值
6) 結構化數組
1、數組的元素都是結構體類型
typedef struct student{ char name[20]; int score; int age;}Student;int main(int argc, const char * argv[]) {Student stu[3]={{"dawang",90,38},{"xiaowang",100,28},{"wangzha",80,18}}; Student max = {0}; Student min = stu[0]; for (int i= 0; i<3; i++) { if (max.score < stu[i].score) { max = stu[i]; } if (min.score > stu[i].score) { min = stu[i]; } } printf("%s %d %d\n",max.name,max.score,max.age); printf("%s %d %d\n",min.name,min.score,min.age);return 0;}
2、按成績排序
typedef struct student{ char name[20]; int score; int age;}Student;int main(int argc, const char * argv[]) {Student stu[3]={{"dawang",90,38},{"xiaowang",100,28},{"wangzha",80,18}};for (int i = 0; i < 2; i++) { for (int j =0 ; j<2-i; i++) { if (stu[j].score < stu[j+1].score) { Student temp = {0}; temp = stu[j]; stu[j] = stu[j+1]; stu[j+1] = temp; } }
} for (int i= 0; i < 3; i++) { printf("%s %d %d\n",stu[i].name,stu[i].score,stu[i].age); }return 0;}
7) 結構體嵌套
typedef struct Date{ int year; int month; int day; }Date;typedef struct student{ char name[20]; int score; int age; Date birthday;}Student;int main(int argc, const char * argv[]) { Student stu = {"zhangsan",88,23,{2003,11,11}}; stu.birthday.year = 2012; printf("%d,%d,%d",stu.birthday.year,stu.birthday.month,stu.birthday.day);return 0;}
8)函數調用結構體
1、.h裡代碼
typedef struct teacher{ char name[30]; int number; int age; }Teacher;void tiger(Teacher t1,Teacher t2);//形參聲明結構體變數void blog(Teacher tea[],int n);
2、.m裡代碼
void tiger(Teacher t1,Teacher t2){ Teacher max = t1.age > t2.age ? t1:t2; printf("%s %d %d\n",max.name,max.number,max.age);}void blog(Teacher tea[],int n){ for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-1-i; j++) { if (tea[j].age< tea[j+1].age) { Teacher temp; temp = tea[j]; tea[j] = tea[j+1]; tea[j+1] = temp; } } } for (int i=0; i<n;i++) { printf("%s %d %d\n",tea[i].name,tea[i].number,tea[i].age); }}
3、main.m裡代碼
Teacher tiger1 = {"haha",2,23}; Teacher tiger2 = {"hehe",3,25}; tiger(tiger1, tiger2); Teacher tea[]={{"dawang",90,38},{"xiaowang",100,28},{"wangzha",80,18}}; blog(tea, 3);
C語言基礎_結構體