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

结构体

时间:2016-02-26 13:54:18      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

结构体定义:

struct 结构体名

{

  数据类型 成员1 ;

  数据类型 成员2;

  .......

};//分号绝对不能丢

ps:结构体类型描述是不占内存空间的,所以不能直接赋值.

简单的定义与引用:

#include <stdio.h>
#include <stdlib.h>
#define NAMESIZE 10 struct birthday_st { int year ; int month; int day ; }; struct student_st { int id ; char name[NAMESIZE]; struct birthday_st birth ; int chinese ; int math; }; /*也可以这样定义 struct student_st { int id ; char name[NAMESIZE]; struct birthday_st { int year ; int month; int day ; }birth; int chinese ; int math; }; */ int main(void) { //TYPE NAME = VALUE;定义法则 struct student_st stu = {111,"xxx",{2011,11,11},60,100};//直接引用 //打印所有成员信息 printf("%d %s %d-%d-%d %d %d \n",stu.id,stu.name,stu.birth.year,stu.birth.month,stu.birth.day,stu.chinese,stu.math); struct student_st *p = &stu;//间接引用 p+1==>跳转一个结构体 printf("%d %s %d-%d-%d %d %d \n",p->id,p->name,p->birth.year,p->birth.month,p->birth.day,p->chinese,p->math); exit(0); }

上述例子:用直接引用和间接引用两种方法将结构体成员定义并打印出来;

结构体占用内存空间的大小:结构体对齐:addr % sizeof()整除:一般以第一个成员占用内存空间大小为标尺;

1.student_st stu:直接引用sizeof(stu)修改成员顺序后大小发生变化。//一般以第一个成员占用内存空间大小为标尺;
技术分享
可以在结构体做不对齐操作:如下
struct student_st
{
    int id ;
    char name[NAMESIZE];
    struct birthday_st birth ;
    int chinese ;
    int math;
}__attribute__((packed));
2.student_st *p:间接引用sizeof(p):就是一个指针占用内存的大小8byts

 

结构体

标签:

原文地址:http://www.cnblogs.com/muzihuan/p/5219948.html

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