欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 08:结构体

08:结构体

2025/9/28 6:28:17 来源:https://blog.csdn.net/qq_51284092/article/details/136118672  浏览:    关键词:08:结构体

结构体

  • 1、为什么需要结构体
  • 2、如何定义结构体
  • 3、怎么使用结构体变量
    • 3.1、赋值和初始化
    • 3.2、结构体变量的输出

1、为什么需要结构体

为了表示一些复杂的事物,而普通的基本类型无法满足实际要求。什么叫结构体
把一些基本类型数据组合在一起形成的一个新的数据类型,这个叫做结构体(复合数据类型)。
列如:

#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、如何定义结构体

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

#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这个成员)

代码

/*通过函数对结构体变量的输入和输出*/	
#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语言也算有了基本的了解。其中还有很多的小细节还需要不断的学习进行丰富

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词