sizeof for a structure with char c[0]

c

Solution

Zero-length arrays are not in the standard C, but they are allowed by many compilers.

The idea is that they must be placed as the very last field in a struct, but they don't occupy any bytes. The struct works as a header for the array that is placed just next to it in memory.

For example:

struct Hdr
{
    int a, b, c;
    struct Foo foos[0]
};

struct Hdr *buffer = malloc(sizeof(struct Hdr) + 10*sizeof(Foo));
buffer->a = ...;
buffer->foos[0] = ...;
buffer->foos[9] = ...;

The standard way to do that is to create an array of size 1 and then substracting that 1 from the length of the array. But even that technique is controversial...

For more details and the similar flexible array member see this document.

Problem

``` struct xyz { int a; int b; char c[0]; }; struct xyz x1; printf("Size of structure is %d",sizeof(x1)); ``` Output: 8 why isn't the size of structure 9 bytes? Is it because the character array declared is of size 0?

Original source

Related problems