在C语言中结构体可以帮助我们自定义数据类型,使我们的编程趋于灵活. 数据类型的本质是一块固定大小的内存空间. 下面我们介绍结构体的声明方式
一,结构体声明方式一
//结构体声明 在声明的时候对结构体重命名
typedef struct Teacher{
char tName[64];
int tAge;
}Teacher;
//结构体类型引用
Teacher t;
二,结构体声明方式二
//结构体声明
struct Student{
char sName[64];
int sAge;
};
//结构体类型引用
struct Student s;
三,代码示意
#include"stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//结构体声明方式一 声明并且重命名
typedef struct Teacher{
char tName[64];
int tAge;
}Teacher;
//结构体声明方式二
struct Student{
char sName[64];
int sAge;
};
int main(){
//方式一类型引用
Teacher t;
//初始化
strcpy_s(t.tName,"T_TOM");
t.tAge = 44;
//方式二类型引用 多了一个struct关键字
struct Student s;
//初始化
strcpy_s(s.sName,"S_JIM");
s.sAge = 15;
printf("Teacher name: %s, Teacher age: %d\n",t.tName, t.tAge);
printf("Student name: %s, Student age: %d\n",s.sName, s.sAge);
return 0;
}
C语言中的结构体允许自定义数据类型,提供了一种更灵活的编程方式。本文详细介绍了结构体的两种声明方法,并通过代码示例进行解释。

1万+

被折叠的 条评论
为什么被折叠?



