【问题标题】:I keep getting this error and it is getting me more and more frustrated, please help me out我不断收到此错误,这让我越来越沮丧,请帮助我
【发布时间】:2021-11-28 02:23:53
【问题描述】:

第 1034 行:字符 9:运行时错误:引用绑定到类型为 'std::vector' (stl_vector.h) 的空指针 摘要:UndefinedBehaviorSanitizer:未定义行为/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h :1043:9

void gameOfLife(vector<vector<int>>& board) {
   vector<vector<int>> newBoard;
    for(int i = 0; i < board.size(); i++){
        for(int j = 0; j < board[i].size(); j++){
            if(board[i][j] == 0 && neibSum(board,i,j) == 3)
                newBoard[i][j] = 1;
            else if(board[i][j] == 1 && neibSum(board,i,j) > 3)
                newBoard[i][j] = 0;
            else if(board[i][j] == 1 && neibSum(board,i,j) < 2)
                newBoard[i][j] = 0;
            else
                newBoard[i][j] = 1;
        }
    }
    for(int i = 0; i < board.size(); i++){
        for(int j = 0; j < board[i].size(); j++){
            cout << newBoard[i][j] << " ";
        }
        cout << endl;
    }
    
}

【问题讨论】:

  • 帖子标题应该能很好地描述您的问题或问题,以便读者了解它的要点(“Java 函数问题”的描述性不是很好)。见:How do I write a good title?
  • @John 问题不是关于 java 的,不幸的是,根据你的简历,你不喜欢 C++。

标签: c++ nullpointerexception runtime-error


【解决方案1】:

您的变量“newboard”是一个大小为 0 的向量。 在:

newBoard[i][j] = 1;

您正在尝试访问未分配的内存。 您需要先分配内存(使用,例如,调整大小)。

   vector<vector<int>> newBoard;
    newBoard.resize(board.size());
    for(int i = 0; i < board.size(); i++){
        newBoard[i].resize(board[i].size());
        for(int j = 0; j < board[i].size(); j++){
...

编辑: p.s.,您可以使用 .at() 函数,而不是 [] 来访问向量元素: newBoard.at(i).at(j) 这包含边界检查。它不会解决你的问题,但它会给你一个更容易理解的错误信息。

【讨论】:

    【解决方案2】:

    你可以在一行中初始化你的板

    #include <vector>
    
    // two constants for you board size
    // stl containers mostly accept std::size_t for their sizes
    constexpr std::size_t board_height_v = 25;
    constexpr std::size_t board_width_v = 80;
    
    enum class cell
    {
        dead,
        alive
    };
    
    int main()
    {
        // I made a cell enum so you can more easily spot where the initial cell value is set.
        // now lets initialize the board to the correct size
        std::vector<std::vector<cell>> newBoard(board_height_v, std::vector<cell>(board_width_v,cell::dead));
    
        return 1;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多