anderspitman
anderspitman

Reputation: 10520

Defining an array with size from a stack variable

This one's got me stumped. If I have a structure:

struct MyType
{
  float *data;
}

And an init function to allocate some memory for the data:

void init(MyType *s, int length)
{
  s->data = (float *)malloc(length*sizeof(float));
}

If I declare an array of MyType using a #define it works as expected:

#define NUM_ELEMENTS 10
MyType myArr[NUM_ELEMENTS];
for (int i=0; i<NUM_ELEMENTS; i++)
{
  init(&myArr[i], 1000);
}

However, if I declare the array using a variable on the stack, I get strange behavior:

int numElements = 10;
MyType myArr[numElements];
...

It's hard to explain what the behavior is without going into detail about more of the code which I think will just confuse things. I know that changing back and forth between the #define and the stack variable decides whether it works or not, so I suspect the problem is here somewhere.

My question is: is everything I'm doing above legal and should it work or am I doing something obviously wrong? I want to use the stack variable so I can define the array size at runtime from a config value.

Upvotes: 0

Views: 107

Answers (1)

user529758
user529758

Reputation:

From a too late comment:

Actually I am using g++ with -std=c++0x. So I guess this is C++

So that's it. You can't have variable-length arrays (VLAs) in C++. That's a C99 feature.

Upvotes: 6

Related Questions