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

C语言基础07

时间:2014-11-05 23:04:40      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:style   color   ar   os   使用   sp   strong   数据   on   

结构体与函数的不同就是函数是由相同数据类型的变量组成,结构中可以有不同数据类型组合。

struct 结构名称 {

  数据类型 成员;    // 注意必须是以分号隔开

  ...

//创建一个构造体

struct student {

  int age;

  char name[45];

  char gender;

  float score;

}

  // 创建结构变量并且为其赋值

struct student stu ={18,"luoshuai",‘m‘,87,5};        

但是:struct student stu1; stu1={18,"luoshuai",‘m‘,87,5}; 

//报错,如果在声明的时候,没有全部赋值,不可以放在后面进行全部赋值。

但是可以逐个的赋值

struct student stu1;

stu1.age =18;

// stu1.name= "lihuahua";   字符串数组 或者数组都不能相互之间直接赋值使用函数。

  strcpy(stu1.name,"luohuahua");

typedef   重新命名。可以简化系统的函数名称

typedef float ff;

ff score = 98.5;

//typedef和结构体组合使用,后面经常使用

typedef struct {

  int age;

  char name[30];

  char gender;

  float weight;

} Cat ;

 

// 结构体的嵌套

typedef struct{

  int year ;

  int mouth;

   int day;

} Birthday;

 

typedef struct{

  int age;

  char name[30];

  Birthday bir;

} People;

People p1 = {"jiesi",29847901093,{1990,6,12}};

printf("%d\n",p1.bir.year);

有一点我们需要注意,字符串数组或者数组都不能直接赋值给其他变量。但是结构体相互之间是可以的。所以如果你想交换数组,可以使用结构体。

typedef struct {

  int age;    4字节

  double score ; 8字节

  char gender;   1字节

  char name[20]; 20字节

} Student;

我们如何知道一个struct在内存占的空间呢?其实很简单,上面已经计算好了每个变量的内存字节占用,加起来就是33个

我们一最大的成员变量数据类型为单位,这里很明显就是Double的8字节,然后 8 * n >=  33 , n必去取值5.最终的内存占用5*8=40个字节。在面试中经常会遇到!

 

 

C语言基础07

标签:style   color   ar   os   使用   sp   strong   数据   on   

原文地址:http://www.cnblogs.com/liruoxuan/p/4077468.html

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