I need to return a structure with a flexible array member from a C function but can\'t figure out why it doesn\'t compile. I know that returning arrays can be achieved by en
Few things:
1) change the struct defenation to:
struct data_array {
long length;
double* data;
^
};
2) This is how you should use malloc to allocate memory for your array:
a.data = malloc (length * sizeof(double));
EDIT
There are too many mistakes, just follow this code:
#include
#include
struct data_array {
long length;
double* data;
};
struct data_array* test (int length) {
struct data_array* a;
a = malloc (sizeof (data_array));
a->data = malloc (length*sizeof(double));
a->length = length;
return a;
}
int main () {
data_array* x;
x = test (5);
for (int i=0; i<5; i++) {
x->data[i] = i+0.5;
}
for (int i=0; i<5; i++) {
printf ("%f\n" , x->data[i]);
}
}
NOTE that you might need to add casting to the types when useing maloc (my visual force me to do so, otherwise it's compile error. But it simply worng).