结构体字节对齐

结构体字节对齐问题

include

if 0 //字节对齐

typedef struct data
{
int a; // 4
char b; // 1 + 1(填充)
short c; // 2 最后整个结构体自身还要对齐
// double d;
}D;
struct data1
{
int a;
double b;
}d;

struct
{
char ch;
}c;

struct
{
char ch[2];
}array;

endif

int main(void)
{
printf(“sizeof(D)= %d.\n”, sizeof(D));
printf(“sizeof(d)= %d.\n”, sizeof(d));
printf(“sizeof(c)= %d.\n”, sizeof(c));
printf(“sizeof(array)= %d.\n”, sizeof(array));

    return 0;

}

include

include

include

pragma pack(2)

struct data // 16
{
int a;
char b;
double c;
}s;

struct data1
{
char ch;
}s1;

pragma pack()

define NUM 5

//检查系统错误的宏.一旦发生了,系统错误就会产生一个错误数字(errno),对应相应的错误字符串。
//C 标准定义了两个值 EXIT_SUCCESS 和 EXIT_FAILURE,可以作为 exit()
// 的参数,来分别指示是否为成功退出。
//exit(参数)传递给的是父进程,或者shell终端

define handle_error(msg) \

            do{perror(msg); exit(EXIT_FAILURE);}while(0)

/*

define PRIN (printf(“1.\n”); printf(“2.\n”);)

void func(int a)
{
printf(“a = %d.\n”, a);
}

define FUNC printf(“所在文件%s所在行数%d.\n”, FILE, LINE)

*/
int main(void)
{
//文件描述符,没有负数
int fd = -1;

    int ret = close(fd);

    if (-1 == ret)
    {
            handle_error("file error!");
    }

/*
int *p = NULL;

    if (NULL == p)
    {
            handle_error("malloc error!");
    }

*/
/*
int flag = 1;
if (flag)
handle_error(“action!”); // printf(“1.\n”); printf(“2.\n”);
else
{
printf(“no action.\n”);
}

    printf("hello 午饭!");

*/
/*
//typeof() 关键字,专门用于获得类型,()里可以放变量名,或者表达式

    FUNC;

    func(NUM);

*/
/*
int a = 3;

// int arr[a] = {};

    int arr_sizeof[sizeof(a)] = {};

*/
/*
// printf(“sizeof(s) = %d.\n”, sizeof(s)); // 1字节对齐 13
// printf(“sizeof(s) = %d.\n”, sizeof(s)); // 2字节对齐 14
printf(“sizeof(s1) = %d.\n”, sizeof(s1)); // 2字节对齐 14
*/

    return 0;

}

include

if 0

    printf("sizeof(s) = %d.\n", sizeof(s));

/*
printf(“sizeof(S) = %d.\n”, sizeof(S));

    printf("&S.a = %p.\n", &S.a);
    printf("&S.p_next = %p.\n", &S.p_next);

*/

endif

    return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值