Initialize array with a non-const function argument

让人想犯罪 __ 提交于 2019-12-24 14:05:36

问题


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
}

回答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.




回答2:


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?




回答3:


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.



来源:https://stackoverflow.com/questions/31027229/initialize-array-with-a-non-const-function-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!