DAY 7
编译器:VS2019;
学习资料
1、B站视频(P35~P41)见链接 【求知讲堂2021C语言/C++视频99天完整版(不断更新中)学完可就业-哔哩哔哩】https://b23.tv/4DzQDY;
结构体
结构体认识
#include<stdio.h>
#include<string.h>
#pragma warning(disable : 4996)
struct Student
{
int num;
char name[20];
char sex;
int age;
float score;
char address[30];
};
struct Day
{
int month;
int day;
int year;
};
void PrintStruct(struct Student* stu)
{
printf("age= %d\n", stu->age);
printf("name = %s\n", stu->name);
}
int main(void)
{
//struct Student stu;
//stu.num = 1;
stu.name=
//strcpy(stu.name, "张三");//#pragma warning(disable : 4996)解决strcpy C4996 'strcpy': This function or variable may be unsafe.
//stu.sex = 'M';
//stu.age = 20;
//stu.score = 99;
//strcpy(stu.address, "上海市陆家嘴");
//
//printf("%d\n", stu.num);
//printf("%s\n", stu.name);
//struct Student student;
//struct Student* stu = &student;//指针初始化 和结构体不同
//strcpy(stu->address ,"上海市高新区");
//stu->age = 21;
//strcpy(stu->name, "李四");
//stu->num = 2;
//stu->score = 61;
//stu->sex = 'W';
//
//printf("学生姓名:%s\n学号:%d\n年龄:%d \n性别:%c\n分数:%d\n家庭住址:%s\n", stu->name, stu->num, stu->age, stu->sex,(int)stu->score,stu->address);
return 0;
}
结构体指针
结构指针定义
- 当一个指针变量用来指向一个结构变量时,称之为结构指针变量。结构指针变量中的值是所指向的结构变量的首地址。通过结构指针即可访问该变量。
结构指针变量的一般形式
- struct 结构名* 结构指针变量名; struct stu*pstu
#include<stdio.h>
#include<string.h>
void PrintStruct(struct Student* stu)
{
printf("age= %d\n", stu->age);
printf("name = %s\n", stu->name);
}
int main(void)
{
//===========================结构体指针======================================
struct Student stu;
strcpy(stu.name, "王五");
stu.age = 22;
PrintStruct(&stu);
}
联合体
联合体认识
#include<stdio.h>
#pragma warning(disable : 4996)
//union Data
//{
// int i;
// char a;
// float j;
//
//}data1, data2, data3;
union Data
{
int i;
char ch;
float j;
};
//union
//{
// int a;
// int b;
// int c;
//}A,B,C;
truct Person
{
int num;
char name[10];
char sex;
char job;
union PersonData
{
int Class;
char postion[10];
}persondata1;
};
int main(int argc, const char* argv[])
{
struct Person person[2];
for (size_t i = 0; i < 2; i++)
{
scanf("%d %s %c %c", &person[i].num, person[i].name, &person[i].sex, &person[i].job);
if (person[i].job == 's')
{
scanf("%d", &person[i].persondata1.Class);
}
if (person[i].job == 't')
{
scanf("%s", person[i].persondata1.postion);
}
}
for (size_t i = 0; i < 2; i++)
{
if (person[i].job == 's')
{
printf("%d %s %c %c %d\n", person[i].num, person[i].name, person[i].job, person[i].sex, person[i].persondata1.Class);
}
if (person[i].job == 't')
{
printf("%d %s %c %c %s\n", person[i].num, person[i].name, person[i].job, person[i].sex, person[i].persondata1.postion);
}
}
return 0;
}
出现的问题
在写代码的时候发现如图1情况,
上一行代码运行报错,下一行代码运行正常