08:结构体

结构体

1、为什么需要结构体

为了表示一些复杂的事物,而普通的基本类型无法满足实际要求。什么叫结构体

把一些基本类型数据组合在一起形成的一个新的数据类型,这个叫做结构体(复合数据类型)。

列如:

c 复制代码
#include <stdio.h>

struct Student//结构体,定义了一个Student的数据类型。由int,float,char类型组成
{
	int age;
	float score;
	char sex;
};//逗号不能省

int main (void)
{
	struct Student st = {15, 66.6, 'F'};//给Student类型命名。
	return 0;
}

2、如何定义结构体

第一种方式:如上面的例子

第二种方式:

c 复制代码
#include <stdio.h>

struct Student
{
	int age;
	float score;
	char sex;
}st;//直接在这里定义数据类型的名字

int main (void)
{
	struct Student st = {15, 66.6, 'F'};
	return 0;
}

推荐使用第一种方式。

3、怎么使用结构体变量

3.1、赋值和初始化

赋值:

复制代码
 第一种:struct Student st = {15, 66.6, 'F'};
 第二种:struct Student st;
         st.age = 15;
         st.score = 66.6;
         st.sex = 'F';

3.2、结构体变量的输出

第一种:

复制代码
printf("%d,%f,%c\n",st.age,st.score,st.sex);

第二种:

复制代码
struct Student* pst = &st;
printf("%d,%f,%c",pst->age,pst->score,pst->sex);

定义一个指针变量pst,用来存放Student数据类型的地址。

pst->age等价于(*pst).age ,也等价于st.age(pst所指向的那个结构体变量中的age这个成员)

代码

c 复制代码
/*通过函数对结构体变量的输入和输出*/	
#include <stdio.h>
#include <string.h>//strcpy使用的声明

void StudentInput(struct Student* pstu);
void StudentOutput(struct Student st);

struct Student
{
	int age;
	float score;
	char name[100];
};

int main (void)
{
	struct Student st;
	StudentInput(&st);
	StudentOutput(st);
	return 0;
}

void StudentInput(struct Student* pstu)
{
	(*pstu).age = 16;
	pstu->score = 66.4f;
	strcpy(pstu->name,"李四");
	
}

void StudentOutput(struct Student st)
{
	printf("%d,%f,%s\n",st.age,st.score,st.name);
}

ok,学到这里,我们对C语言也算有了基本的了解。其中还有很多的小细节还需要不断的学习进行丰富

相关推荐
水饺编程8 小时前
第2章:Linux 基础,切换用户
linux·c语言·汇编
知识分享小能手9 小时前
C学习教程,从入门到精通,C语言学生信息管理系统 — 知识点详解(18)
c语言·学习·1024程序员节
爱读书的小胖10 小时前
LeetCode 55 跳跃游戏 C 语言解题分析
c语言·数据结构·算法·leetcode·1024程序员节
pipixia2003310 小时前
C++ 面试高频:namespace 的 6 个知识点,从 using 到匿名命名空间
c语言·学习·算法·嵌入式·命名空间·c++面试·匿名命名空间
Navigator_Z11 小时前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode
爱读书的小胖14 小时前
LeetCode 274 H 指数 C 语言解题分析
c语言·算法·leetcode·1024程序员节
Pointer Pursuit14 小时前
Linux环境变量
linux·服务器·c语言·链表·1024程序员节
CHHH_HHH15 小时前
【Linux网络篇】初识网络与Socket编程基础
linux·服务器·c语言·开发语言·网络·后端·1024程序员节
思麟呀15 小时前
BTree的原理与 C++ 完整实现
c语言·数据结构·c++·算法·1024程序员节
qq_4086068616 小时前
C_Primer_Plus_chapter17_exercise3
c语言·1024程序员节