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
}
3
  • either as new char[n] or std::vector Commented Jun 24, 2015 at 13:02
  • There is no standard way for this, some compilers do support it by extension (stackoverflow.com/a/5377465/3747990). A vector would be a better alternative. Commented Jun 24, 2015 at 13:04
  • It may work if it's a inline function and it's called with a int literal. Commented Jun 24, 2015 at 13:10

3 Answers 3

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.

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

6 Comments

... or to allocate memory on heap?
@Kris Correct. Removed the misleading comment.
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...)
@MattMcNabb Is the explanation in the link I provided correct? (Thank you for the pointer, btw, this is something I did not know).
I have tried using size_t initialized with n, but I still get the same type error.
|
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?

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.