pointers - How to include a dynamic array INSIDE a struct in C? -
i have looked around have been unable find solution must asked question. here code have:
#include <stdlib.h> struct my_struct { int n; char s[] }; int main() { struct my_struct ms; ms.s = malloc(sizeof(char*)*50); }
and here error gcc gives me: error: invalid use of flexible array member
i can compile if declare declaration of s inside struct
char* s
and superior implementation (pointer arithmetic faster arrays, yes?) thought in c declaration of
char s[]
is same as
char* s
the way have written , used called "struct hack", until c99 blessed "flexible array member". reason you're getting error (probably anyway) needs followed semicolon:
#include <stdlib.h> struct my_struct { int n; char s[]; };
when allocate space this, want allocate size of struct plus amount of space want array:
struct my_struct *s = malloc(sizeof(struct my_struct) + 50);
in case, flexible array member array of char, , sizeof(char)==1, don't need multiply size, other malloc you'd need if array of other type:
struct dyn_array { int size; int data[]; }; struct dyn_array* my_array = malloc(sizeof(struct dyn_array) + 100 * sizeof(int));
edit: gives different result changing member pointer. in case, (normally) need 2 separate allocations, 1 struct itself, , 1 "extra" data pointed pointer. using flexible array member can allocate data in single block.
Comments
Post a Comment