What is wrong with my C++ code


  • 0
    A
    class NumArray {
    public:
        NumArray(vector<int> &nums) {
            for (int i = 0; i<nums.size(); i++)
                this->myArray[i]=nums[i];
        }
    
        int sumRange(int i, int j) {
            int sum;
            for (i; i<=j; i++)
                sum+=myArray[i];
            return sum;
        }
        
    private:
        int *myArray;
    };

  • 0
    P

    'myArray[i]' is not allocated.
    _this->myArray=new int[nums.size()]_should be called.

    And even 'myArray[i]' is allocated, when the size of 'nums' is 0, as the input is '[]', 'myArray[i]' is non-sense and you got a Runtime Error.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.