#C语言#在学习分配地址时,为什么取地址后返回了类似index的东西

先上代码(学习阶段,可能写的有些乱):

#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;
}

运行结果

img

就是这里,为什么这里是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;
}

运行结果

img

struct test *alignf 这是一个指针,&(alignf)是指针的地址, &(alignf->a) 这东西没用的,一般(alignf->a)就是它的值
地址建议用%p十六进制打印

alignf = (struct test *)malloc(sizeof(struct test)*4);
//动态申请结构体数组,上面你申请sizeof(struct test)+4)个空间,然后强转为struct test *这个指针形式,是个啥
alignf[0]->b[0] = 2;
...
alignf[3]->b[0] = 2;//正确赋值形式,你上面那个的那个数组成员b都越界了