码迷,mamicode.com
首页 > 其他好文 > 详细

C 基础 - 结构

时间:2017-09-11 10:25:40      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:之间   运算   语言   方法   相互   structure   foo   class   str   

 

 

C语言提供 结构变量(struct variable) 来扩展表示数据的能力。

 

需求:创建一个图书目录。

打印每本书的各种信息: 书名,作者,价格,出版社等。 

 

可以使用C结构来描述数据。

 

结构声明:描述了一个结构的组织布局。

1 struct book {            /* structure template: tag is book     */
2     char title[MAXTITL];
3     char author[MAXAUTL];
4     float value;
5 };                       /* end of structure template           */

 

并没有描述实际的数据对象,只是描述了对象由什么组成。

 

定义结构变量

结构有两层含义

一、结构布局

二、定义结构变量

/* 把library 声明为一个使用book结构布局的结构变量 */
struct book library  

或者可以这样写

struct book {    /* book标记可以省略 */           
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
 } library;   /* 声明的右花括号后跟变量名 */   

/* book类型的结构数组 */
struct book library[MAXBKS];

/* 声明初始化结构指针 */
struct book * library;

/* 赋值,需要加上取址符 */
library = &suprise;

 

初始化结构

struct book library = {
  "C Primer Plus",
  "史蒂芬 普拉达",
  "80"
};

 

 

还可以使用初始化器来初始化成员

/* 只初始化book结构中 value成员 */
struct
book gift = { .value = 10.99 }; /* 按照任意顺序初始化成员 */ struct book surpise = { .value = 25.99, .author = "Steven", .title = "C Primer Plus" };

 

 

 

访问结构成员

点来访问结构中的成员

library.value

.value  .author  .title 相当于结构的下标。

 

用指针访问结构中的成员

如果 him == &library, 那么him->income

如果 him == &library[0], 那么him->income 即是 library[0].income

 

另一种方法: & 与 * 是一组互逆运算

fellow[0].income == (*him).income   /*一定要加括号,因为.的优先级高*/

 

 

结构嵌套

struct names {      /* 第一个结构 */
  char fist[LNE];
  char last[LEN];
};

struct guy {
  struct names handle;   /* 结构嵌套 */
  char favfood[len];
  char job[LEN];
  float income;
};

struct guy fellow = {
{David Zhang},
"Fish",
"Software Engineer",
"9999.00",
};

/* 访问嵌套中结构的成员 */
fellow.handle.first

 

向函数传递结构的信息

结构之间可以相互赋值

 

 

 

联合是一种数据类型

枚举

 

typedef

 

C 基础 - 结构

标签:之间   运算   语言   方法   相互   structure   foo   class   str   

原文地址:http://www.cnblogs.com/elewei/p/7502824.html

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