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));
}
}
you're creating temporary variable a
in function calculateFlexibility
, then you store pointer to f.flex
variable, but after function is ended - a
is gone from memory, so your f.flex
pointer is now pointing to nowhere
if you want to have really variable length, you should do something like this:
Flexibility calculateFlexibility()
{
Flexibility f;
f.flex = (int*)malloc(....);
return f;
}
and at the end of program:
free(f.flex);
for proper arguments of malloc I suggest you to read: http://en.cppreference.com/w/c/memory/malloc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.