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;
}