Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 指向c+中相同内存块的数组+;?_C++_Arrays_Memory_Memory Management_Dynamic Programming - Fatal编程技术网

C++ 指向c+中相同内存块的数组+;?

C++ 指向c+中相同内存块的数组+;?,c++,arrays,memory,memory-management,dynamic-programming,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

我有一个奇怪的问题。我用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阵列改变了,我不知道为什么。我只是添加了这句话,我想知道为什么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
for(int y=0;y

你是说“<代码>(y+h-1)%h <代码>代替<代码>(Y-1)%H < /C> >?/P>嘿,谢谢你的回答!我已经检查过谷歌,并且似乎--1%是C++中的负值。(Y+H-1)%H应该工作,我会尝试:

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