Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Created June 29, 2022 07:34
Show Gist options
  • Save louisswarren/dd9be326372399ee63ad42fd677221c7 to your computer and use it in GitHub Desktop.
Save louisswarren/dd9be326372399ee63ad42fd677221c7 to your computer and use it in GitHub Desktop.
Flexible array members in flexible array members are allowed
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct a {
char x;
char buf[];
};
struct b {
char y;
struct a fub[];
};
int
main(void)
{
int len_fub = 5;
int len_buf = 2;
size_t sz = sizeof(struct b) + len_fub * (sizeof(struct a) + len_buf);
struct b *p = malloc(sz);
printf("sizeof(struct a) = %d\n", (int)sizeof(struct a));
printf("sizeof(struct b) = %d\n", (int)sizeof(struct b));
printf("*p is size %d\n", (int)sz);
memcpy(p, "123456789ABCDEF", sz);
assert('1' == p->y);
assert('2' == p->fub[0].x);
assert('3' == p->fub[0].buf[0]);
assert('4' == p->fub[0].buf[1]);
assert('4' == p->fub[1].buf[0]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment