首页 > 编程知识 正文

c语言结构体总结,c语言中的结构体有什么作用

时间:2023-05-06 14:02:47 阅读:148389 作者:649

在说结构体之前,让我们先看看类型和变量

例如int a;

int是类型名称,a是变量名称

变量名是我们自己定义的,可以更改为其他名称,但不能更改int、char等类型名称

结构可以自己定义类型名称

然后定义student类型和chen变量

范例

结构//结构

{

int age; //成员

int score;

(;

struct student chen; //student是类型名称,chen是变量名称

我们创建了一个名为student的结构类型名称。 然后,可以使用此结构定义名为chen的变量。

让我们比较一下struct student chen和int a。 其中struct是结构类型。

student相当于int,chen相当于a

实际上,即使省略struct,直接写成student chen也没错,但一般会加上struct声明是结构体类型

更简单的方法是如下所示

结构//结构

{

int age; //成员

int score;

(}chen;

直接声明了student型的chen变量

让我们看看使用方法

struct student//类型

{

int age; //成员

int score;

(; //注意不要错过冒号

sudent Chen={ 19,100 }; //赋值,chen的age为19,chen的score为100

printf(%d(n ),chen.age );

printf(%d(n ),chen.score );

/*

输出结果:

19

100

Press any key to continue

*/

要使用结构的成员,请首先定义该结构的变量(例如student chen ),然后使用变量名称.成员名称(例如chen.age )。

写student.age,注意不要与类型名称混淆。

赋值需要student Chen={ 19,100 }; 19和100分别被分配给变量chen的age和score

当然chen.age=19,chen.score=100; 赋值

如果你用的是简写方法

也可以在定义结构时赋值

struct student//类型

{

int age; //成员

int score;

(Chen={ 19,100 } );

让我们看看typedef

上一个示例中的类型名称是struct student,如果我想省略stucrt该怎么办

定义结构体还有一种方法

typedef struct

{

int age; //成员

int score;

}student; //类型名称

student chen; //定义变量

使用了typedef关键字,将struct之后的类型名称student放在了下面。 这样,在定义变量时就不必写struct了

但是,请注意,此方法不要混淆类型名称和变量名

让我们来比较一下

//普通方法

struct student

{

int age; //成员

int score;

(}chen; //变量名

chen.age=19;

请参见----------------------------------------- -

如何使用typedef

typedef struct

{

int age; //成员

int score;

}student; //类型名称

student chen; //定义变量名

chen.age=19; //正确

student.age=19; //错了!

使用typedef时,类型名称student被放在下面。 这里本来就是放变量名chen的地方,所以容易混乱。 要使用结构中的成员,需要变量名.成员,因此如果如上所述将类型名称student错当成变量名,则会写student.age并导致错误

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。