结构体的成员偏移地址和字节对齐

 

p没有操作内存,在cpu中运用不会出错。

 

#define  _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct teacher
{
	int id;
	char name[64];
	int age;
};

int main(void)
{
	struct teacher t1 = {0};
	struct teacher *p = &t1;

	int age = t1.age;
	int id = t1.id;

	int id_offsize = (int)&(((struct teacher *)0)->id);
	int name_offsize = (int)&(((struct teacher *)0)->name);
	int age_offsize = (int)&(((struct teacher *)0)->age);

	printf("id_off: %d, name_off:%d, age_off:%d\n", id_offsize, name_offsize, age_offsize);

	int age_off = (int)(&(p->age)) - (int)p;

	printf("age_off : %d\n", age_off);

	return 0;
}

 

 

#define  _CRT_SECURE_NO_WARNINGS 
#pragma	pack(2)					//8字节对⻬
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct	A
{
	char					c;					//1byte
	double				d;					//8byte
	short					s;					//2byte
	int					i;					//4byte
};

struct B
{
	int a;
	//double d;
	char c1;
	char c2;
	short s1;
	short s2;
};

int main(void)
{
	int size_A = 0;

	size_A = sizeof(struct A);

	printf("size_A : %d\n", size_A);

	int size_B = 0;
	size_B = sizeof(struct B);

	printf("size_B : %d\n", size_B);


	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值