【问题标题】:Arrays pointing to the same block of memory in c++?指向c ++中同一块内存的数组?
【发布时间】:2013-01-19 18:40:57
【问题描述】:

我有一个奇怪的问题。我在 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 数组的最后一列(我对此感兴趣)。当我添加以下语句时,就在 // 基本情况下方:

p[0][0] = 3;

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

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

谢谢!

【问题讨论】:

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


    【解决方案1】:

    您的代码具有未定义的行为。考虑当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

    【讨论】:

    • 您好,谢谢您的回答!我在谷歌上查了一下,似乎 -1 % 3 在 C++ 中是负数。 (y+h-1)%h 应该可以,我会试试 :)
    猜你喜欢
    • 1970-01-01
    • 2019-04-07
    • 2016-03-05
    • 2019-04-12
    • 1970-01-01
    • 2021-04-15
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多