kesari anjana
kesari anjana

Reputation: 21

2D array elements not being read properly

The output is a string of numbers of entire row/column instead of a single number. Can someone please help me in this?

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */  
int t;
cin>>t;
while(t--){
    int n,m,cnt=0;
    cin>>n>>m;
    for(int i=0;i<=n+1;i++){
        for(int j=0;j<=m+1;j++){
            if(i==0||i==n+1||j==m+1||j==0) G[i][j]=0;
            cin>>G[i][j];
        }
    }
 cout<<G[1][2]<<endl;//this gives wrong o/p

return 0; }

Upvotes: 1

Views: 68

Answers (2)

Ron
Ron

Reputation: 15501

Most likely you are reading out of bounds due to a i <= n + 1 and j <= m + 1 conditions in your for loops thus invoking undefined behavior resulting in a corrupted stack which explains the output you are seeing. Modify the boundaries to: i < n and j < m. Arrays are zero indexed in C++. First array element is accessed via somearray[0] and the last element is somearray[n-1] not somearray[n] which is what you are trying to access in your code. The same goes for multi-dimensional arrays. The statement of:

cout << G[i][j] << endl; 

is wrongly placed outside the for loops. It should be inside the inner for loop. The array should be defined as a second statement in your while loop:

int G[n][m]; // Avoid VLAs

That being said variable length arrays are not part of the C++ standard and you should prefer std::vector and std::array to raw arrays.

Upvotes: 2

gsamaras
gsamaras

Reputation: 73366

Assuming G is a 2D array of size n x m, then you go out of bounds here:

for(int i=0;i<=n+1;i++) {
    for(int j=0;j<=m+1;j++)

since array indexing starts from 0, and ends at size - 1.

As a result, your code invokes Undefined Behavior. To avoid that, simply change your double for loop to this:

for(int i = 0; i < n; i++) {
    for(int j = 0;j < m; j++)

Upvotes: 2

Related Questions