码迷,mamicode.com
首页 > 编程语言 > 详细

C语言结构体(struct)简单应用个人理解

时间:2016-06-15 18:57:23      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

struct用法

第一种 只有结构体定义

struct student{

  char name[20];

  int age;

  char class;

};

这里的struct student就相当于int等数据类型,可以用struct student定义变量,如struct student aaa,就类似定义int aaa;注意struct 和student合在一起才能表示一个结构类型。

第二种 结构体定义后面加一个变量

struct student{

  char name[20];

  int age;

  char class;

}student_1;

这里就相当于第一种的结构体多增加了一行语句,定义了一个变量,也就是说等价于

struct student{

  char name[20];

  int age;

  char class;

};

struct student  student_1;

第三种 唯一变量的结构体定义

struct {

  char name[20];

  int age;

  char class;

}student_1;

也就是说没有了student这个结构体名称,这样只能使用结构体变量student_1,如果还需要定义相同类型的结构体,必须重新定义,不能使用这个结构体定义,也就是说这个结构体只有唯一的一个变量student_1。

 

typedef  struct的用法

 

typedef为C语言的关键字,作用是为一种数据类型定义一个新名字。这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)。

 

在编程中使用typedef目的一般有两个,一个是给变量一个易记且意义明确的新名字,另一个是简化一些比较复杂的类型声明。

 

第一种  上面第二种用法前面直接加typedef

typedef struct student{

  char name[20];

  int age;

  char class;

}student_1;

这语句实际上完成两个操作:
1) 定义一个新的结构类型

struct student{

  char name[20];

  int age;

  char class;

};
2) typedef为这个新的结构起了一个名字,叫student_1。
typedef struct student student_1; (对比typedef int student_1来进行理解)
  因此,student_1实际上相当于struct student,这样定义一个变量的时候,既可以用struct student aaa,也可以用student_1 aaa。student_1成了一个数据类型。

如果有逗号,比如

typedef struct student{

  char name[20];

  int age;

  char class;

}student_1,student_2;

可以先理解成

struct student{

  char name[20];

  int age;

  char class;

}student_1;

struct student{

  char name[20];

  int age;

  char class;

}student_2;

这样再加上typedef,同上分析,也就是说struct student有两个别名,分别是student_1和student_2,都可以代替struct student定义变量。也就是说有三种用法,struct student aaa;student_1 aaa;student_2 aaa都是等价的。

第二种  上面第三种用法前面直接加typedef

typedef struct {

  char name[20];

  int age;

  char class;

}student_1;

根据唯一性,即定义变量的时候只能是student_1 aaa;

C语言结构体(struct)简单应用个人理解

标签:

原文地址:http://www.cnblogs.com/st-moon/p/5588321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!