I want to store a variable length array in a struct, and I use a pointer for this purpose. However, if I retrieve the stored array, I get the wrong values back. In the example below, I get the output "1 0", while you would expect the output "1 2".
#include <stdio.h>
typedef struct Flexibility {
int *flex;
} Flexibility;
Flexibility calculateFlexibility()
{
int a[2];
a[0] = 1;
a[1] = 2;
Flexibility f;
f.flex = a;
return f;
}
void main()
{
Flexibility f;
f = calculateFlexibility();
int i;
for(i = 0; i < 2; i++)
{
fprintf(stdout, "%i ", *(f.flex + i));
}
}
agets out of scope when you return fromcalculateFlexibility, thusf->flexpoints to an array that doesn't exist anymore.