0

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.

9
  • 7
    Just like for plain C-style arrays, the size must be a compile-time constant (this is actually a requirement for all template value arguments). If you want an "array" whose size is known only at run-time you must use std::vector. Commented Mar 30, 2022 at 8:21
  • 3
    I'm also very curious why you need an array (or vector) with the same size as an existing string? What is the use of the array (or vector)? What problem is it supposed to solve? Can't you use the string itself? Commented Mar 30, 2022 at 8:23
  • Thanks @Someprogrammerdude, I couldn't think of std::vector, saved my time. Commented Mar 30, 2022 at 8:27
  • 4
    Why do you want this? Use the string itself as the array Commented Mar 30, 2022 at 8:37
  • 3
    As long as you're working with text, use std::string. Everything you can do with a std::vector, you can also do with a std::string. Commented Mar 30, 2022 at 8:53

2 Answers 2

4

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.

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

Comments

1

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

6 Comments

Thank you, I'll work with vector now.
You're welcome. You can also add elements to the vector on the fly : ` for(int i=0; i<str.size(); i++) v.push_back(str[i]); `
const is not sufficient. With a constant size there would be same error: godbolt.org/z/3oTzs9aze
You can't assign a non-constant to a constant value either. You can only assign a number directly to a constant, for example: const int N = 10;
hm? int x = 42; const int y = x; and const int a = 42; int b = a; are both completely fine. I suppose you actually mean a constant expression that can be evaluated at compile time. const isnt that
|

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.