先上代码(学习阶段,可能写的有些乱):
#include <stdio.h>
#include <malloc.h>
#define c(x) #x
#define ad(x) printf("adress of %s: %lu\n",c(x),&(x))
struct test
{
int a;
char b[1];
};
void align(void){
struct test *alignf;
ad(alignf);
ad(alignf->a);
ad(alignf->b);
alignf = (struct test *)malloc(sizeof(struct test)+4);
for (size_t i = 0; i < 5; i++)
{
alignf->b[i]= i+1;
}
printf("\n");
ad(alignf);
ad(alignf->a);
ad(alignf->b);
free(alignf);
}
int main(){
align();
return 0;
}
运行结果
就是这里,为什么这里是0和4啊
如果把for循环去掉或者直接赋值则正常
#include <stdio.h>
#include <malloc.h>
#define c(x) #x
#define ad(x) printf("adress of %s: %lu\n",c(x),&(x))
struct test
{
int a;
char b[1];
};
void align(void){
struct test *alignf;
ad(alignf);
ad(alignf->a);
ad(alignf->b);
alignf = (struct test *)malloc(sizeof(struct test)+4);
// for (size_t i = 0; i < 5; i++)
// {
// alignf->b[i]= i+1;
// }
alignf->b[0] = 2;alignf->b[1] = 2;
alignf->b[2] = 2;alignf->b[3] = 2;
alignf->b[4] = 2;
printf("\n");
ad(alignf);
ad(alignf->a);
ad(alignf->b);
free(alignf);
}
int main(){
align();
return 0;
}
运行结果