Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set variable length with variable

Tags:

c++

arrays

What I'm trying to do right now is to create an array with a length that is defined by a variable. However, when I put the variable in the array length, it gives me a "Variable length array of non-POD element type 'glm::vec2'" error. However, if I replace the variable with an actual number, the error goes away. Why does this happen and how can I fix this?


int numtriangles = sector1.numtriangles;


glm::vec2 tex[test]; //Using a variable generates an error
glm::vec3 vertices[10]; //No error here

like image 952
TheAmateurProgrammer Avatar asked May 15 '26 20:05

TheAmateurProgrammer


2 Answers

You cannot have variable length arrays(VLA) in standard C++.
Variable length arrays are not allowed by the C++ Standard. In C++ the length of the array needs to be a compile time constant. Some compilers do support VLA as a compiler extension, but using them makes your code non-portable across other compilers.

You can use, std::vector instead of an VLA.

like image 55
Alok Save Avatar answered May 17 '26 08:05

Alok Save


See this question Is there a way to initialize an array with non-constant variables? (C++)

Short answer is no you cannot directly do this. However you can get the same effect with something like

int arraySize = 10;
int * myArray = new int[arraySize];

Now myArray is a pointer to the array and you can access it like an array like myArray[0], etc.

You can also use a vector which will allow you to have a variable length array. My example allows you to create an array with a variable initailizer however myArray will be only 10 items long in my example. If you aren't sure how long the array will ever be use a vector and you can push and pop items off it.

Also keep in mind with my example that since you've dyanmically allocated memory you will need to free that memory when you are done with the array by doing something like

delete[] myArray;

Here is a little sample app to illustrate the point

#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    int arraySize = 10;
    int * myArray = new int[arraySize];
    myArray[0] = 1;
    cout << myArray[0] << endl;

    delete[] myArray;
}
like image 26
devshorts Avatar answered May 17 '26 08:05

devshorts