嵌入式-C语言基础:结构体

2023-02-12,,,

数组只能存放一种类型的数据,而结构体内可以存放不同类型的数据。

#include<stdio.h>
#include <string.h> struct Student
{
char name[32];
int age;
int height;
int weight;
}; int main()
{
//结构体赋值
struct Student stu1;
strcpy(stu1.name,"nsal");
stu1.age=45;
stu1.height=150;
stu1.weight=200;
printf("name=%s\n",stu1.name);
//结构体赋值
struct Student stu2={"hhh",12,45,45};
//结构体数组
//int arr[3]={1,2,3};
struct Student Stus[3]={
{"hhh",12,45,45},
{"ttt",16,24,45},
{"kkk",18,23,45},
};
//遍历结构体数组
int size=sizeof(Stus)/sizeof(Stus[0]);
for(int i=0;i<size;i++)
{
printf("name=%s\n",Stus[i].name);
}
return 0;
}

输出结果:

name=nsal
name=hhh
name=ttt
name=kkk

结构体的使用很简单,但是细节往往很容易忽略,例如结构体最后很容易少掉;结构体变量也是以;分开

嵌入式-C语言基础:结构体的相关教程结束。

《嵌入式-C语言基础:结构体.doc》

下载本文的Word格式文档,以方便收藏与打印。