> 文章列表 > C结构体中末尾的data[0]

C结构体中末尾的data[0]

C结构体中末尾的data[0]

    一个结构中包含char data[0],数组的长度为零。

    在linux内核中,结构体中经常用到data[0]。
    

struct ac_buffer
    {
        int len;            // 长度
        char data[0];   // 起始地址
    };

    在这个结构中,data是一个数组名;但该数组没有元素;
   
    这种声明方法可以巧妙的实现C语言里的数组扩展。设计的目的是让数组长度是可变的,根据需要进行分配。方便操作,节省空间。

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

struct ac
{
    int i;
    char data[0];
};

int main(int argc, char* argv[])
{
    void * p = NULL;
    char buf[10] = "abcdefghi";    
    struct ac * info = (struct ac *)malloc(sizeof(struct ac) + 10);

    info->i = 9;
    p = (void*)info->data;

    printf("%d\\n", sizeof(struct ac));        // 4
    printf("info address:%p\\n", info, p);    // 0x56542a4742a0   ---> ac结构体的首指针
    printf("   p address:%p\\n", p);            // 0x56542a4742a4   ---> p指向的地址,ac结构体的第二个变量的地址+4
    printf("   p address:%p\\n", &p);        // p 自身的地址

    strncpy((char*)p, buf, info->i);
    printf("%s\\n", (char*)p);                // abcdefghi

    return 0;
}