温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C语言中结构体是什么

发布时间:2022-03-03 14:48:30 来源:亿速云 阅读:214 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关C语言中结构体是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

一.结构体定义

C语言结构体由一系列相同或者不同类型的数据构成的集合,结构体类型就是以struct关键字定义的数据类型。

结构体的格式如下:

struct 结构名称 { 
    结构体所包含的数据成员,包括变量数组等
} 结构变量 ;//结构变量可以指定一个或多个

举例:

struct Student
{
	char name[10];
	char sex[2];
	int age;
}Stu

二.实例演示

先看下结构体变量如何初始化

C语言中结构体是什么

#include <stdio.h>
#include <string.h>
struct Student
{
        char name[10];
        char sex[5];
        int age;
}Stu = {"Mike","man",22};

int main(int argc, char *argv[])
{
        printf("name:%s\nsex:%s\nage:%d\n",Stu.name,Stu.sex,Stu.age);
}

初始化结构体变量很简单,直接在结构体变量后面赋值。
结果:

C语言中结构体是什么

结构体作为函数参数

#include <stdio.h>
#include <string.h>
//定义Student结构体
struct Student
{
        char name[10];
        char sex[5];
        int age;
}Stu;

void print(struct Student stu)
{
        printf("Student name:%s\n",stu.name);
        printf("Student sex:%s\n",stu.sex);
        printf("Student age:%d\n",stu.age);
}

int main(int argc, char *argv[])
{
        struct Student stu1;
        strcpy(stu1.name,"will");
        strcpy(stu1.sex,"man");
        stu1.age = 20;
        print(stu1);
        //Stu
        Stu.age=11;
        print(Stu);
}

C语言中结构体是什么

从这个示例可以看出:将结构体作为参数传入函数,定义结构体时,我们可以在;前面定义结构体变量, 这样就不需要再定义结构变量,如:struct Student stu1;假设stu1在定义结构体时就定义变量,那么就可以直接赋值。

结果:

C语言中结构体是什么

可以看出第二个学生打印,因为在定义结构体时就已经定义结构变量,所以可以直接赋值。

结构体指针

实例演示,传入结构体指针

C语言中结构体是什么

#include <stdio.h>
#include <string.h>
struct Student
{
        char name[10];
        char sex[5];
        int age;
}Stu;

void print(struct Student *stu)
{
        printf("Student name:%s\n",stu->name);
        printf("Student sex:%s\n",stu->sex);
        printf("Student age:%d\n",stu->age);
}

int main(int argc, char *argv[])
{
        struct Student stu1;
        strcpy(stu1.name,"will");
        strcpy(stu1.sex,"man");
        stu1.age = 20;
        print(&stu1);
        Stu.age=11;
        print(&Stu);
}

这里的实例和上面例子的区别主要是:
1.将定义的变量改为指针struct Student *stu。
2.指针赋值时使用->。
3.使用打印函数时,改为取地址。

结果一致

三.typedef struct 和 struct的区别

1、声明不同

1)、struct:struct可以直接使用结构体名字声明结构体。
2)、typedef struct:typedef struct为修饰结构体,结构体有了别名,通过结构体别名声明结构体。

2、访问成员变量不同

1)、struct:struct定义的结构体变量,可直接访问结构体成员

2)、typedef struct:typedef struct定义的结构体变量,不可直接访问结构体成员,必须显式的通过结构体变量来访问成员。

3、重新定义不同

1)、struct:想重新定义struct结构体的话,必须重写整个结构体。

2)、typedef struct:想重新定义typedef struct结构体的话,可以通过别名来继承结构体进行重新定义。
举例:

C语言中结构体是什么

可以看到:
使用typedef struct定义的结构体,我们通常是使用别名进行操作,而且在使用时也简化了使用方法,例如:Stu s1,相当于声明对象一样,如果使用struct,那么就要写成struct Student stu1;。

如果直接使用结构体名称那么会报错:

错误示例:

C语言中结构体是什么

报错结果:

C语言中结构体是什么

改回别名操作,结果:

C语言中结构体是什么

感谢各位的阅读!关于“C语言中结构体是什么”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI