结构体变量注释和结构体数组练习(已注释)代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
struct Student
{
char name[20];
int age;
char sex;
float score;
char addr[30];
};
int main() {
//练习结构体变量
struct Student s = { "Alice", 20, 'F', 90.5, "123 Main St" };
printf("%s %d %c %f %s\n", s.name, s.age, s.sex, s.score, s.addr);
strcpy(s.name, "hhh");
printf("%s %d %c %f %s\n", s.name, s.age, s.sex, s.score, s.addr);
//这是结构体数组的练习
/*struct Student s[3] = {
{"Alice", 20, 'F', 90.5, "123 Main St"},
{"Bob",22 ,'M',85.0, "456 Elm St"},
{"Charlie", 21, 'F', 92.0, "789 Oak St"}
};*/
/*struct Student s[3];
for (int i = 0; i < 3; i++)
{
scanf("%s%d %c%f%s", &s[i].name, &s[i].age, &s[i].sex, &s[i].score, &s[i].addr);
}
for (int i = 0; i <3; i++)
{
printf("%s %d %c %f %s\n",s[i].name,s[i].age, s[i].sex, s[i].score, s[i].addr);
}*/
return 0;
}
typedf关键字的使用(在定义结构体后面加上结构体别名和指针别名,在主函数用的时候直接当一个自定义类型使用)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
typedef struct student {
char idcard[20];
char name[20];
char sex;//男是M,女是F
} stu, *pstu;
int main() {
//练习结构体变量
stu s;
pstu p;
p = &s;
printf("请依次输入学号,姓名,性别(F或M):");
scanf("%s %s %c", p->idcard, p->name, &p->sex);
printf("学号:%s,姓名:%s,性别:%c",p->idcard,p->name,p->sex);
return 0;
}
结果:
结束~