Line 923: Char 9: runtime error: reference binding to null pointer of type 'std::vector >' (stl_vector.h)


記錄Leetcode刷題遇到的錯誤

程序代碼(C++):

    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        int rows = matrix.size();
        int cols = matrix[0].size();
        if(rows == 0 || cols == 0) return false;
        return binarySearch(matrix, target, 0, cols - 1, rows, cols);
    }

報錯代碼:

執行出錯信息:  Line 923: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator<int> >' (stl_vector.h)
最后執行的輸入:
[]
0

報錯原因:

輸入為空時的判斷。當rows=0的時候,數組不存在元素,也就不存在matrix[0],matrix[0]產生越界。

程序修改:

    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        int rows = matrix.size();
        if(rows == 0) return false;
        int cols = matrix[0].size();
        if(cols == 0) return false;
        return binarySearch(matrix, target, 0, cols - 1, rows, cols);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM