C语言中内存偏移量

时间:2022-04-10 08:17:22
#include	<stdio.h>
#include	<stddef.h>

typedef struct _A {
    char         a;        
    int          b;    
    float        c;
    double       d;
    int          *pa;
    char         *pc;
    short        e;
    long long    l;
} A;

#define	AOI(m, type)	{ offsetof(struct _A, m), sizeof(type), #type, #m }
struct offinfo {
	int 		offset;
	int 		size;
	const char 	*type;
	const char 	*name;
} ainfo[] = {
	AOI(a, char),
	AOI(b, int),
	AOI(c, float),
	AOI(d, double),
	AOI(pa, int*),
	AOI(pc, char*),
	AOI(e, short),
	AOI(l, long long),
	{ 0 },
};


#pragma pack(pop)
int 
main(int argc, char *argv[]) 
{
	int i;

	for (i = 0; ainfo[i].name != NULL; i++)
		printf("%s %s size %d, offset at %d\n", 
			ainfo[i].type, ainfo[i].name, 
			ainfo[i].size, ainfo[i].offset);

	return 0;
}