Array declaration inside a function

Hi guys, is it safe to do stuff like:

1
2
3
4
5
6
7
8
9
10
void func(int v[], int size) {
 int array_local[size];

 for(int i = 0; i < size; i++) array_local[i] = v[i];

 /*
 Other stuff...
 */

}


Or i can stumble in some kind of error?
Last edited on
This will not work in standard C++ because the size of the array has to be a compile time constant. Some compilers (e.g. GCC/MinGW) allows this as an extension to the langauge so I guess it depends on if you want to depend on certain compilers or if you only want to write standard C++.

Another problem could be if the array is too big. The stack is usually not as big as the heap so you are more limited in space than if you had dynamically allocated the array, using new or std::vector.
Last edited on
In C99, this would compile. It will be safe if the array is small enough (typically, can fit in the stack); otherwise there would be undefined behaviour.

In conforming C++, this won't compile cleanly; the size of an array must be a constant known at compile time.

Use a vector instead. https://www.mochima.com/tutorials/vectors.html

1
2
3
4
5
6
7
8
9
#include <vector>

void func(int v[], int size) {

    std::vector<int> array_local( v, v+size ) ; // initialise from contents of c-style array

    // ... Other stuff...

}
Topic archived. No new replies allowed.