第15天:结构类型

109 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情

1. 结构:一个东西整合一堆不同数据类型的变量

结构:复合数据类型
声明结构类型

#include <stdio.h>

int main(int argc, char const *argv[]) {
	struct date {
		int month;
		int day;
		int year;
	};
	struct date today;
	today.month = 07;
	today.day = 31;
	today.year = 07;
	printf("Today's date is %i-%i-%i.\n",
	       today.year, today.month, today.day);
	return 0;
}

分析:

  • 结构体里有三个整型元素,每次结构体出现的时候,这三个元素都是一起出现的。
  • 注意结构体的大括号结束后有一个分号,初学者容易忘掉,这也是个易错点
    • 没写分号程序会报错

记得我当年c语言期末考试的时候,结构体的题因为胆怯,甚至都没有打开看一下,导致这个题没有做,没能做到精益求精,实在是非常遗憾。现在看到结构体的知识点和代码,似乎没有我想象的那么难

总结:

  • 和本地变量一样,在函数内部声明的结构类型只能在函数内部使用
  • 所以通常在函数外部声明结构类型,这样就可以被多个函数所使用了
    • 在函数外部声明后,以下的函数都可以调用这个结构体
#include <stdio.h>

struct date {
	int month;
	int day;
	int year;
};

int main(int argc, char const *argv[]) {

	struct date today;
	today.month = 07;
	today.day = 31;
	today.year = 07;
	printf("Today's date is %i-%i-%i.\n",
	       today.year, today.month, today.day);
	return 0;
}

2. 声明结构的形式

形式1

struct point {
    int x;
    int y;
};
struct point p1,p2;
  • p1和p2都是point里面
  • point有x和y的值
  • 上面的struct point p1,p2是定义了一个结构体类型的变量,变量名是p1和p2

形式2

struct {
    int x;
    int y;
}p1,p2;
  • p1和p2都是一种无名结构,里面有x和y,p1和p2都是变量,这个结构没有名字

形式3

struct point {
    int x;
    int y;
}p1,p2;
  • p1和p2都是point
  • 里面有x和y的值

小结

  • 对于第一和第三种形式,都声明了结构point。但是第二种形式没有声明point,只是定义了两个变量

3. 总结

这节课学习了结构体的相关知识,学习了结构体的定义和使用方法,结构体是一种可以包含多个不同的数据类型的变量的一种数据类型,感觉是枚举的进阶版。