结构体字节对齐问题
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;
}