1

Is there any way to initialize an array with a non-const integer, or to make the existing variable constant in order to make it a valid argument?

bool f( const char s[], const int n )
{
    char c[n]; // error: expression must have a constant value
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
user3650284
  • 137
  • 1
  • 3
  • 10

3 Answers3

1

No, not in the general case. Use vector<char> c(n) instead.

Simplified, almost correct explanation: if you don't know what n is at compile time, neither does the compiler. So it cannot put aside memory for the array. This is why vector exists.

You can always use &c[0] to get the pointer to char if you need it elsewhere.

But it is possible in C99, apparently. Thanks to @Matt McNabb for pointing this out. If you can wait a few years you might be able to compile it in C++, too. In the meanwhile, use vector.

If you insist to have an "array" in C++, you would have to do something like:

char* c = new char[n];

If your program does not run forever, or do this too often, you can even just leave it as it is and not bother deleting. Tools like Valgrind might complain though.

Community
  • 1
  • 1
  • 1
    ... or to allocate memory on heap? – user3650284 Jun 24 '15 at 13:04
  • @Kris Correct. Removed the misleading comment. –  Jun 24 '15 at 13:09
  • 1
    The "Explanation" isn't right: C does allow runtime-sized arrays, so the compiler can clearly figure it out. The reason C++ doesn't is because it has repercussions throughout the whole type system, and nobody has been able to figure out how to cope with this in C++ yet. (think templates...) – M.M Jun 24 '15 at 13:10
  • @MattMcNabb Is the explanation in the link I provided correct? (Thank you for the pointer, btw, this is something I did not know). –  Jun 24 '15 at 13:15
  • I have tried using size_t initialized with n, but I still get the same type error. – user3650284 Jun 24 '15 at 13:19
  • @user3650284 Changing the type will not help; the problem is that the _value_ of `n`, in the general case, is not known at compile time. –  Jun 24 '15 at 13:21
1

Depending on the source of n, the answer is probably no. In case n can be a constexpr, then the answer is yes.

See this SO post for more information about constexpr: When should you use constexpr capability in C++11?

Community
  • 1
  • 1
Kris
  • 2,108
  • 18
  • 19
1

n is located on a stack. In this case a compiler needs to know the size of n at compile time. You can dynamically allocate memory by operator new, or use std::vector.

monnef
  • 3,903
  • 5
  • 30
  • 50