C语言结构体
希望今年夏天的遗憾能成为你秋天的惊喜。。。。
---- 网易云热评
一、结构体概念
可以简单理解为把不同数据类型放到一起的数组
二、结构体声明与初始化
1、先声明结构体类型再定义变量
2、同时定义变量
3、直接定义结构体类型变量
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
struct Aiyou
{
int year;
char name[100];
char* zdg;
};
struct Aiyou ay;
struct Aiyou ay1 ={2016,"周杰伦的床边故事","告白气球"};
struct Aiyou ay2;
int main() {
printf("%d\n",ay1.year);
printf("%s\n", ay1.name);
printf("%s\n", ay1.zdg);
ay.year = 2015;
strcpy_s(ay.name,100,"哎呦,不错哦");//ay.name是数组名,是常量所以不能直接赋值
ay.zdg = "听爸爸的话";
printf("%d\n", ay.year);
printf("%s\n", ay.name);
printf("%s\n", ay.zdg);
struct Aiyou *p;
p = &ay2; //让p有所指向
p->year = 2015;
strcpy_s((*p).name, 100, "十二新作");
p->zdg = "明明就";
printf("%d\n", p->year);
printf("%s\n", (*p).name);
//printf("%s\n", p[0].name);
printf("%s\n", p->zdg);
system("pause");
return 0;
}
运行结果:
三、其他初始化方法
直接在结构体初始化
struct Aiyou
{
int year;
char name[100];
char* zdg;
}ay={2015,“aiyou”,“bucuo”},ay1,ay2;
无变量名
struct
{
int year;
char name[100];
char* zdg;
}ay,ay1,ay2;
四、结构体数组
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
struct Aiyou
{
int year;
char name[100];
char* zdg;
};
int main() {
struct Aiyou a[5];
a[0].year = 2016;
strcpy_s(a[0].name,100, "周杰伦的床边故事");
a[0].zdg = "告白气球";
(a + 1)->year = 2015;
strcpy_s((a+1)->name, 100, "哎呦,不错哦");
(a + 1)->zdg = "听爸爸的话";
(*(a + 2)).year = 2012;
strcpy_s((*(a + 2)).name, 100, "十二新作");
(*(a + 2)).zdg = "明明就";
//通过指针操作
struct Aiyou* p;
p = &a[0];
p[3].year = 2011;
strcpy_s(p[3].name, 100, "惊叹号");
p[3].zdg = "Mine Mine";
(p + 4)->year = 2010;
strcpy_s((p +4)->name, 100, "跨时代");
(p + 4)->zdg = "烟花易冷";
for (int i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
printf("专辑名称:%s,主打歌:%s,发行时间:%d\n", a[i].name, a[i].zdg, a[i].year);
}
system("pause");
return 0;
}
运行结果:
五、结构体嵌套
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
struct Bucuo
{
int year;
char* name;
};
struct Aiyou
{
struct Bucuo bc;
char* zdg;
};
int main() {
struct Aiyou ay;
ay.bc.year = 2016;
ay.bc.name = "周杰伦的床边故事";
ay.zdg = "告白气球";
printf("专辑名称:%s,主打歌:%s,发行时间:%d\n", ay.bc.name, ay.zdg, ay.bc.year);
struct Aiyou* p = &ay;
p->bc.year = 2015;
p->bc.name = "哎呦,不错哦";
p->zdg = "听爸爸的话";
printf("专辑名称:%s,主打歌:%s,发行时间:%d\n", p->bc.name, ay.zdg, p->bc.year);
system("pause");
return 0;
}
运行结果:
专辑名称:周杰伦的床边故事,主打歌:告白气球,发行时间:2016
专辑名称:哎呦,不错哦,主打歌:听爸爸的话,发行时间:2015
欢迎关注公众号:顺便编点程