'Invalid use of flexible array member error
typedef struct {
void *end;
void *start;
int size;
int arrs [];
} st;
void *doStuff(void *starter, void *ender) {
st *s = (st *) malloc(sizeof(st));
s->end = ender;
s->start = starter;
int sayz = 1;
s->size = (int) (ender - starter);
int a [s->size];
memset(a, 0, sizeof a);
s->arrs = a; // This line gives error
return s;
}
the line "st->arrs = a;" gives me the "Invalid use of flexible array member" error. Does anybody know how I can save an array inside a structure? The language is C
Solution 1:[1]
This is what you want, assuming starter and ender point to char objects. I've also cleaned up your indenting and formatting.
typedef struct {
void *end;
void *start;
ptrdiff_t size; // Note that a diff of pointers should be a ptrdiff_t
int arrs[];
} st;
st *doStuff(void *starter, void *ender) {
ptrdiff_t size = (char*)ender - (char*)starter; // Calculate size first so it's available to use in malloc
st *s = malloc(size + sizeof st);
s->end = ender;
s->start = starter;
s->size = size;
memset(s->arrs, 0, size * sizeof s->arrs[0]); // since array is allocated, no need to create a redundant array
return s;
}
Solution 2:[2]
A flexible array member is not a pointer; you do not assign an address or an array to it. You allocate space for it as part of the space you allocate for the array, and then you use it like an array. Change st *s = (st *) malloc(sizeof(st)); to st *s = malloc(sizeof *s + N * sizeof *s->arrs);, where N is the number of elements you want for the array.
Then you can initialize the array to zero with memset(s->arrs, 0, N * sizeof *s->arrs);.
Note that ender - starter is not proper C code. The type of ender and starter is void *, and the C standard does not define the behavior of subtracting pointers to void. GCC does, but this gives you a number of bytes, not, in general, a number of array elements. To subtract ender and starter properly, use (T *) ender - (T *) starter, where T is the type of object they point to.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SGeorgiades |
| Solution 2 | Eric Postpischil |
