Is it possible to use nested flexible arrays (flexible array of flexible arrays) in C?
I tried the following code to test flexible arrays:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int x;
int y;
} node;
typedef struct {
int len;
node elem[];
} cell;
int cell_size = 3;
int main(void) {
cell *set = malloc(sizeof *set + cell_size * sizeof set->elem[0]);
set->len = cell_size;
for (int j = 0; j < cell_size; j++) {
set->elem[j].x = j;
set->elem[j].y = j * 10;
}
printf("set size: %d\n", set->len);
for (int j = 0; j < cell_size; j++) {
printf("x: %d, ", set->elem[j].x);
printf("y: %d\n", set->elem[j].y);
}
return 0;
}
The output is:
set size: 3
x: 0, y: 0
x: 1, y: 10
x: 2, y: 20
Here everything is fine as expected. Allocated space for set
is 28 bytes.
But when I tried to modify this code like this to put flexible array inside other array:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int x;
int y;
} node;
typedef struct {
int len;
node elem[];
} cell;
typedef struct {
int len;
cell group[];
} obj;
int cell_size = 3;
int obj_size = 4;
int main(void) {
obj *set = malloc(
sizeof *set + obj_size * sizeof (
sizeof (cell) + cell_size * sizeof(node)
));
set->len = obj_size;
for (int i = 0; i < obj_size; i++) {
set->group[i].len = cell_size;
for (int j = 0; j < cell_size; j++) {
set->group[i].elem[j].x = j;
set->group[i].elem[j].y = j * 10 + i;
}
}
printf("set size: %d\n", set->len);
for (int i = 0; i < obj_size; i++) {
printf("group size: %d\n", set->group[i].len);
for (int j = 0; j < cell_size; j++) {
printf("x: %d, ", set->group[i].elem[j].x);
printf("y: %d\n", set->group[i].elem[j].y);
}
}
return 0;
}
Allocated space for set
is 20 bytes and the output is wrong:
set size: 4
group size: 3
x: 3, y: 3
x: 3, y: 0
x: 3, y: 1
group size: 3
x: 3, y: 3
x: 0, y: 3
x: 1, y: 13
group size: 3
x: 3, y: 0
x: 3, y: 1
x: 13, y: 2
group size: 3
x: 0, y: 3
x: 1, y: 13
x: 2, y: 23
Even if I set malloc
manually to any reasonable value the output is still incorrect. I think this is because the compiler don't know the size of group[]
member in the top structure (obj
). However I didn't get any compiler errors or warnings (GCC 6.3.0).
And I don't know how to set this size and make compiler process this code correctly.