c - Return structure with flexible array member -


i need return structure flexible array member c function can't figure out why doesn't compile. know returning arrays can achieved encapsulating them in struct follows:

struct data_array {     long length;     double data[]; }; 

my function looks this:

struct data_array test (int length) {     struct data_array a;     double* b = malloc (1000);     a.length = 1000;     a.data = b;     return a; } 

however, compiler returns: "invalid use of flexible array member".

according book "21st century c", data array in struct handled pointer (which makes sense me). has not been initialized , therefore there should no memory been allocated hold data. (even compiler doesn't know how memory needed it). have allocate memory , assign return variable.

so, why compiler returns error? , how can solve problem?

you may either declare data incomplete array (an array without specified dimension) or declare pointer. (an incomplete array inside struct must last member , called flexible array member.)

if declare incomplete array, structure contains length element , many array elements allocate it. must allocate base size of structure plus space elements, with:

struct data_array *b = malloc(sizeof *b + numberofelements * sizeof *b->data); 

however, cannot return structure allocated in way, because return type of function must complete type. structures flexible array members not permitted. however, return pointer structure. so, return b not *b.

if declare data pointer, create structure , separately allocate space data point to, with:

struct data_array b; b.length = numberofelements; b.data = malloc(numberofelements * sizeof *b.data); 

here code samples. first, flexible array member:

struct data_array {     long length;     double data[]; };  struct data_array *test(size_t numberofelements) {      struct data_array *b = malloc(sizeof *b + numberofelements * sizeof *b->data);      // put code here test result of malloc.      b->length = numberofelements;      return b; } 

or pointer:

struct data_array {     long length;     double *data; };  struct data_array test(size_t numberofelements) {      struct data_array b = { numberofelements,          malloc(sizeof *b + numberofelements * sizeof *b->data) };      // put code here test result of malloc.      return b; } 

Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -