c++ - 在 C++ 中指向同一个内存块的数组?

标签 c++ arrays memory memory-management dynamic-programming

我有一个奇怪的问题。我在 C++ 中有以下代码:

int grid[h][w]; int dp[h][w]; int p[h][w];

for(int y = 0; y < h; y++)
    for(int x = 0; x < w; x++)
        cin >> grid[y][x];

// base case
for(int y = 0; y < h; y++) dp[y][0] = grid[y][0];


// fill rest
for(int x = 1; x < w; x++)
{
    for(int y = 0; y < h; y++)
    {
        dp[y][x] = min(dp[y][x-1], min(dp[(y-1)%h][x-1], dp[(y+1)%h][x-1])) + grid[y][x];
    }
}

cout << "dp: " << endl;
for(int y = 0; y < h; y++) cout << dp[y][w-1] << endl;

如您所见,在最后几行中,我打印了 dp 数组的最后一列(我对此感兴趣)。当我添加以下语句时,就在//base case 的下方:

p[0][0] = 3;

我的 dp 数组改变了,我不知道为什么。我只添加了那条语句,我想知道为什么 dp 数组会发生变化,以及如何防止这种情况发生。

有人可以向我解释为什么会这样吗?

谢谢!

最佳答案

您的代码有未定义的行为。考虑当 y = 0 时以下循环内发生的情况:

for(int y = 0; y < h; y++)
{
    dp[y][x] = min(dp[y][x-1], min(dp[(y-1)%h][x-1], dp[(y+1)%h][x-1])) + grid[y][x];
                                   ^^^^^^^^^^^ out of bounds since -1%h equals -1

你是想说 (y+h-1)%h 而不是 (y-1)%h 吗?

关于c++ - 在 C++ 中指向同一个内存块的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14417528/

相关文章:

c - 记录动态内存分配使用情况

python - Heroku 上的 Redis 管理

c++ - 如何在 google mock for c 中自动生成 mock

c++ - 以下代码的时间复杂度..?

javascript - 将项目添加到数组然后序列化()javascript

php - 如何通过路径访问多维数组元素?

c++ - 当 C++ 程序结束时,指针是否从内存中释放?

c++ - 使用 boost::asio::async_read 时出现段错误

c++ - 从 boost::labeled_graph 获取节点标签

javascript - 检查包含数组的数组