2

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));
    }

}
1
  • a gets out of scope when you return from calculateFlexibility, thus f->flex points to an array that doesn't exist anymore. Commented Oct 18, 2013 at 1:34

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.