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

后端 未结 6 1795
半阙折子戏
半阙折子戏 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条回答
  •  伪装坚强ぢ
    2020-11-27 20:02

    To do what you want, you will need to use dynamic allocation. In which case I would seriously suggest using vector instead - it is the "right" thing to do in C++.

    But if you still don't want to use vector [why you wouldn't is beyond me], the correct code is:

     void foo(int variable_int){
        int *a   = new int[variable_int]();   // Parenthesis to initialize to zero.
        ... do stuff with a ... 
        delete [] a;
     }
    

    As others have suggest, you can also use calloc, which has the same effect of initializing to zero, but not really the "c++" solution.

提交回复
热议问题