在Linux内核代码中,我发现了以下无法理解的内容.
struct bts_action {
u16 type;
u16 size;
u8 data[0];
} __attribute__ ((packed));
Run Code Online (Sandbox Code Playgroud)
代码在这里:http://lxr.free-electrons.com/source/include/linux/ti_wilink_st.h
零元素数据数组的需求和目的是什么?
C代码喜欢这个:
#include <stdio.h>
#include <unistd.h>
#define DIM(a) (sizeof(a)/sizeof(a[0]))
struct obj
{
int a[1];
};
int main()
{
struct obj *p = NULL;
printf("%d\n",DIM(p->a));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个对象指针p是NULL,所以,我认为这p->a是非法的.但是我已经在Ubuntu14.04中测试了这段代码,它可以正确执行.所以,我想知道为什么......
注意:原始代码在int a[0]上面,但我已经改变了,int a[1]因为每个人似乎都挂在那而不是实际的问题,这是:
sizeof(p->a)当表达式p等于时,表达式是否有效NULL?
struct xyz {
int a;
int b;
char c[0];
};
struct xyz x1;
printf("Size of structure is %d",sizeof(x1));
Run Code Online (Sandbox Code Playgroud)
输出:8 为什么结构的大小不是 9 个字节?是不是因为声明的字符数组的大小为 0?