C语言之结构体知识大总结


一、什么是结构体

为了更好地模拟现实,需要把各种基本数据类型组合在一起构成一种新的复合数据类型,我们把这种自定义的数据类型称为结构体。结构体是程序员根据实际需求,把各种基本数据类型组合在一起构成的一种新的复合数据类型

二、结构体的定义

结构体的定义方式共有3种,这里只用最常见也最常用的一种方式定义,即:

struct 结构体名
{
   
    
    
	成员列表;
}; // 注意这里的分号不能省略

举个例子:

struct Student
{
   
    
    
	int age;
	float score;
	char gender;
};

三、结构体变量的定义

结构体与我们经常使用的基本数据类型一样,它也是一种数据类型,所以我们可以用这一数据类型定义其对应的变量,我们把用结构体类型定义的变量称为结构体变量。定义结构体变量的方式如下所示:

#include <stdio.h>

struct Student // 定义结构体
{
   
    
    
	int age;
	float score;
	char gender;
};

int main()
{
   
    
    
	struct Student stu; // 定义结构体变量
	
	return 0;
}

四、结构体变量的初始化

#include <stdio.h>

struct Student // 定义结构体
{
   
    
    
	int age;
	float score;
	char gender;
};

int main()
{
   
    
    
	struct Student stu = {
   
    
     15, 66.5, 'M' }; // 初始化结构体变量
	
	return 0;
}

五、结构体变量的赋值

定义结构体变量后,我们可以对其中的成员进行赋值操作,但与初始化不同的是,需要通过结构体变量名.成员名的方式对结构体变量中的每个成员单独赋值。代码如下所示

#include <stdio.h>

struct Student // 定义结构体
{
   
    
    
	int age;
	float score;
	char gender;
};

int main()
{
   
    
    
	struct Student stu; // 定义结构体变量

	stu.age = 15; 		// 对结构体变量中的age成员赋值
	stu.score = 66.5;	// 对结构体变量中的score成员赋值
	stu.gender = 'M';	// 对结构体变量中的gender成员赋值

	return 0;
}

六、引用结构体变量中的成员

方法1:结构体变量名.成员名

#include <stdio.h>

struct Student // 定义结构体
{
   
    
    
	int age;
	float score;
	char gender;
};

int 

猜你喜欢

转载自blog.csdn.net/weixin_65334260/article/details/125607089