Search code examples
c++arraysdev-c++

Why did my array values get updated to random values?


I have a grid with 2 rows and 3 columns. I do an operation where I do not update any element of the grid, rather just access it. Somehow, my grid has been updated with random values

#include <iostream>
using namespace std;
int main(){

int grid[2][3]{{1,3,5},
                {2,4,-10}};
int row{sizeof(sizeof(grid)/sizeof(grid[0]))};
int col{sizeof(grid[0])/sizeof(int)};
int dp[3][4]{};
for(auto &y:grid){
    for(auto x:y){
        cout<<x<<"\t";
    }
    cout<<endl;
}
for(int i{1};i<=row;i++){
    for(int j{1};j<=col;j++){
        dp[i][j]=grid[i-1][j-1]+max(dp[i][j-1],dp[i-1][j]);
    }
}
cout<<"++++++++++++++++++++++++"<<endl;
for(auto &y:grid){
    for(auto x:y){
        cout<<x<<"\t";
    }
    cout<<endl;
}
}

output:

1       3       5  
2       4       -10  
++++++++++++++++++++++++  
1       4       8  
7       4       3  

When I run this code on online IDE like cpp.sh I am not getting the problem. But I'm using devC++ and maybe this is some specific issue with devC++ rather than my code.


Solution

  • Your calculation of row is incorrect:

    int row{sizeof(sizeof(grid)/sizeof(grid[0]))};
    

    this gives the value of 8 (on my machine, but in general it gives the size of an int). You have an extra sizeof in there. This means you are invoking undefined behavior in your second loop, by indexing out of bounds.

    Instead do:

    int row{sizeof(grid)/sizeof(grid[0])};
    

    which gives 2 as needed.

    Here's a demo.