1. 結構就是多個變數的集合:
#include <stdio.h>int main(void){ struct Rec { int x; int y; }; struct Rec r1; r1.x = 111; r1.y = 222; printf("%d, %d", r1.x, r1.y); getchar(); return 0;}
2. 定義時同時聲明變數:
#include <stdio.h>int main(void){ struct Rec { int x,y; } r1,r2; r1.x = 111; r1.y = 222; r2.x = 333; r2.y = 444; printf("%d, %d\n", r1.x, r1.y); printf("%d, %d\n", r2.x, r2.y); getchar(); return 0;}
3. 定義時同時聲明變數並賦值:
#include <stdio.h>int main(void){ struct Rec { int x,y; } r1 = {777,888}; printf("%d, %d\n", r1.x, r1.y); getchar(); return 0;}
#include <stdio.h>int main(void){ struct Rec { char name[12]; short age; } r1 = {"ZhangSan", 12}; printf("%s, %u", r1.name, r1.age); getchar(); return 0;}
4. 聲明變數是賦初值:
#include <stdio.h>int main(void){ struct Rec { char name[12]; short age; }; struct Rec r1 = {"ZhangSan", 12}; printf("%s, %u", r1.name, r1.age); getchar(); return 0;}
5. 聲明後給字串賦值有點麻煩:
#include <stdio.h>#include <string.h>int main(void){ struct Rec { char name[12]; short age; }; struct Rec r1; strcpy(r1.name, "ZhangSan"); r1.age = 18; printf("%s, %u", r1.name, r1.age); getchar(); return 0;}
6. 如果在定義時直接聲明變數, 可省略結構名:
#include <stdio.h>int main(void){ struct { char name[12]; short age; } r1 = {"ZhangSan", 12}; printf("%s, %u", r1.name, r1.age); getchar(); return 0;}
7. 通過 scanf 賦值:
#include <stdio.h>int main(void){ struct Rec { char name[12]; short age; } r1; printf("name: "); scanf("%s", r1.name); printf("age: "); scanf("%d", &r1.age); printf("Name: %s; Age: %d", r1.name, r1.age); getchar(); getchar(); return 0;}