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

后端 未结 6 1793
半阙折子戏
半阙折子戏 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:04

    C++ does not support variable-length arrays. Instead, you'll need to allocate the array dynamically:

    std::vector a(variable_int);
    

    or since you say you don't want to use a vector for some reason:

    class not_a_vector
    {
    public:
        explicit not_a_vector(size_t size) : a(new int[size]()) {}
        ~not_a_vector() {delete [] a;}
        int & operator[](size_t i) {return a[i];}
        int   operator[](size_t i) const {return a[i];}
    
        not_a_vector(not_a_vector const &) = delete;
        void operator=(not_a_vector const &) = delete;
    
    private:
        int * a;
    };
    
    not_a_vector a(variable_int);
    

    UPDATE: The question has just been updated with the "C" tag as well as "C++". C (since 1999) does support variable-length arrays, so your code should be fine in that language.

提交回复
热议问题