网站首页 > 技术文章 正文
在了解结构体是一种复杂的数据类型之后,我们来看看结构体是如何定义的。定义结构体有三种方法
方法一,创建结构体,声明结构体变量
struct Student{
int age;
char sex;
};
声明结构体变量
struct Student st = {30,’男’};
方法二,在定义结构体时,直接定义变量名
struct Student{
int age;
char sex;
} st;
方法三,直接定义结构体变量名
struct{
int age;
char sex;
} st;
此方法定义不清晰,不知道结构体名称是声明。
其中最常用的是方式一,先定义结构体,再使用结构体声明变量。在使用结构体时,建议使用方式一。
结构体赋值与初始化
定义结构体Student。
struct Student{
int age;
char sex;
};
(1)声明结构体变量st,同时进行赋值。
struct Student st = {30,’男’};
(2)声明结构体变量st2,再通过形如st2.age这样的形式进行赋值
struct Student st2;
st2.age = 30;
st2.sex = ‘女’;
程序演示,使用方式一定义结构体,并进行赋值
#include
struct Student{
int age;
char sex;
};
int main(void){
struct Student st;
st.age = 30;
st.sex = 'm';
printf("年龄:%d,性别:%c",st.age,st.sex);
return 0;
}
以上示例定义了结构体Student,声明结构体变量st,使用结构体变量名.成员的形式进行赋值并输出。
猜你喜欢
- 2025-03-12 结构体(Struct)
- 2025-03-12 Mysql数据库tinyint,int,bigint,char,varchar究竟用哪个?
- 2025-03-12 吃透c语言难点—指针
- 2025-03-12 动手打造深度学习框架:基本数据结构与算法
- 2025-03-12 C语言指针访问数组基础知识,理解各种符号的意义
- 2025-03-12 C语言结构体中只有一个数组,这么做有什么好处?是多此一举吗?
- 2025-03-12 C++提高部分_C++函数模板_案例_数组排序---C++语言工作笔记083
- 2025-03-12 C++20 新特性(6):new表达式也支持数组大小推导
- 2025-03-12 C#学习随笔—操作BIN文件(读,写,替代)
- 2025-03-12 C语言之数组
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- c++int转char (75)
- static函数和普通函数 (76)
- el-date-picker开始日期早于结束日期 (70)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- js数组插入 (83)
- linux删除一个文件夹 (65)
- mac安装java (72)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)