an array of zero length

an array of zero length is a hack which is used to for variable size of array, since the element of zero length in a struct does not exist from the point of view of the storage, while it exists from the point of the compiler.

 

Here is a sample code.

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

struct st{
int len;
char a[0];
};

int main()
{
int n=10;
st *s=(st*)malloc(sizeof(int)+sizeof(char)*n);
s->len=n;
int i=0;
for(i=0; i<s->len;i++)
{
s->a[i] = i+'0';
}
s->a[s->len] = '\0';
printf("sizeof(st)=%d\n", sizeof(st));
printf("len=%d, a=%s\n", s->len, s->a);

free(s);
return 0;
}

 

-------------

torstan> ./a.out
sizeof(st)=4
len=10, a=0123456789

posted on 2013-04-07 19:56  Torstan  阅读(231)  评论(0编辑  收藏  举报

导航