dimanche 5 février 2023

Runtime Error: reference binding to null pointer of type 'int' (stl_vector.h), product of array except self

While solving a Product of array except self on leetcode , I encountered an error:

runtime error: reference binding to null pointer of type 'int' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9

Here is my code to the problem:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int leftarr[nums.size()];
        int rightarr[nums.size()];
        int n = nums.size();
        int prod=1;
        for(int i=0;i<n;++i){
            prod *= nums[i];
            leftarr[i]= prod;
        }
        prod=1;
        for(int j=n-1;j>=0;--j){
            prod *= nums[j];
            rightarr[j]= prod;
        }
        vector<int> output;
        output[0]= rightarr[n-1];
        output[n-1]= leftarr[n-2];
        for(int i=1;i<n-1;++i){
          output.push_back(leftarr[i-1]*rightarr[i+1]);
        }

        return output;
    }
};

My approach to solve this problem: Take two arrays, leftarr and rightarr and store the cumulative left and right multiplication at respective index, then take output vector and multiply left and right multiplication and get the output.

So, could any one of you pls tell me why this error occurs and what is wrong with my code?

Aucun commentaire:

Enregistrer un commentaire