In redis there is a struct called sdahdr
:
struct sdahdr
{
int len;
int free;
char buf[];
}
Why not use char *buf
instead, and why is sizeof(sdahdr) == 8
instead of 12?
In redis there is a struct called sdahdr
:
struct sdahdr
{
int len;
int free;
char buf[];
}
Why not use char *buf
instead, and why is sizeof(sdahdr) == 8
instead of 12?
The char buf[]
is a placeholder for a string. Since the max length of the string is not known at compiletime, the struct reserves the name for it, so it can be properly adressed.
When memory is allocated at runtime, the allocation must include the length of the string plus the sizeof the struct, and then can pass around the structure with the string, accessible via the array.
char *s = "test";
struct sdahdr *p = malloc(sizeof(struct sdahdr)+strlen(s)+1);
strcpy(p->buf, s);