Home > Mobile >  initializing array with variable
initializing array with variable

Time:03-30

I'm having an issue initializing std::array with variable.

std::string str = "Hello world this is just testing";

int size = str.size();

std::array<char, size> arr;

Returns following error:

note: 'int size' is not const
error: the value od 'size' is not usable in a constant expression
note: in template argument for type 'long long unsigned int'

I'm newbie, please help.

CodePudding user response:

You cannot use variables as template arguments unless they are compile time constant. Hence, the size of std::array must be compile time constant. What you're trying to do is not possible. Same limitation applies to array variables as well.

std::string already internally owns a dynamic array of char, so you probably don't need std::array at all.

CodePudding user response:

You need to pass a constant expression as the size to the array data structure. If you want to assign variable length to a data structure, you can use std::vector<char> v(size); instead of an array. I also think you can use variable length with arrays if you use the GCC compiler

  • Related