首页 > 解决方案 > C++ 访问冲突 - 可能是由于表?

问题描述

在主要功能中,我有以下内容。

int numRows = rowSequence.length() + 1;
int numCols = columnSequence.length() + 1;

int** twoDimTable = new int* [numRows];
for (int rowIndex = 0; rowIndex < numRows; rowIndex++) 
{
    twoDimTable[rowIndex] = new int [numCols];
}

//updating table
for (int i = 0; i <= numRows; i++)
{
    for (int j = 0; j <= numCols; j++)
    {
        if (i == 0 || j == 0)
            twoDimTable[i][j] = 0; 

// when I start running my code I receive an unhandled exception right at the 'if' 
// statement: Access violation writing location. I looked at other similar 
// situations, but cannot seem to understand  the specific issue

        else if (rowSequence[i - 1] == columnSequence[j - 1])
            twoDimTable[i][j] = twoDimTable[i - 1][j - 1] + 1;

        else
            twoDimTable[i][j] = max(twoDimTable[i - 1][j], twoDimTable[i][j - 1]);
    }
}

标签: c++

解决方案


一个问题是你的 for 循环是错误的。numRows并且numCols不是有效的索引,因此它们不应包含在您的迭代中。

也就是说,而不是这样:

for (int i = 0; i <= numRows; i++)
{
    for (int j = 0; j <= numCols; j++)
    { 
        [...]
    }
}

...你应该有这个:

for (int i = 0; i < numRows; i++)
{
    for (int j = 0; j < numCols; j++)
    { 
        [...]
    }
}

推荐阅读