How to create an array when the size is a variable not a constant?

后端 未结 6 1752
半阙折子戏
半阙折子戏 2020-11-27 19:31

I\'ve got a method that receives a variable int. That variable constitutes an array size (please, don\'t offer me a vector). Thus, I need to init a const int inside my metho

6条回答
  •  -上瘾入骨i
    2020-11-27 19:49

    You can easily make a const variable from a non-const variable by writing const int bar = variable_int; - however that won't help you. In C++ the size of an array with automatic storage must be a compile-time constant. You can't turn a variable into a compile-time constant, so what you want is simply not possible.

    Depending on your needs, you could make a a pointer and allocate memory using new (and then later delete it) or, if the parameter to foo will always be known at compile-time, you could turn foo into a template function like this:

    template void foo() {
        int a[n] = {0};
    }
    

提交回复
热议问题