Search code examples
cgccvisual-c++compiler-errors

Why for loop doesn't work for 2D array with an overflow but still works for 1D array


The for loop to store values to two 1D arrays can store and print values even with an overflow but why a program to store values to 2D array using for loop doesn't run when there is an overflow?

The following program runs:

#include <stdio.h>

int main()
{
 int i, a[5], b[6];
 for (i = 0; i <= 6; i++)
 {
    a[i] = i;
    b[i] = i;
 }

 for (i = 0; i <= 6; i++)
 {
   printf(" %d", a[i], b[i]);
 }

 return 0;
}

But why the following program doesn't run?

#include <stdio.h>

int main()
{
int i, j, a[5][5];

for (i = 0; i <= 5; i++)
{
    for (j = 0; j <= 5; j++)
    {
        a[i][j] = j;
    }
}


for (i = 0; i <= 5; i++)
{
    for (j = 0; j <= 5; j++)
    {
        printf(" %d", a[i][j]);
    }
printf("\n");
}

return 0;
}

I tried to store the values in 2D array using nested for loop but it doesn't run. However, the program runs when 1D array is used.


Solution

  • First one that you shared works because you are lucky. When you say int a[5] this means you allocated 5 unit for integer and it starts from zero to four. It does not include five.

    Fixed code first one:

    #include <stdio.h>
    
    int main()
    {
     int i, a[5], b[6];
     for (i = 0; i <= 4; i++)
     {
        a[i] = i;
        
     }
     for (i = 0; i <= 5; i++)
     {
        b[i] = i;
        
     }
    
     for (i = 0; i <= 5; i++)
     {
       if(i<5)
         printf("a= %d\nb= %d", a[i], b[i]);
       else
         printf("b=%d",b[i]);
     }
    
     return 0;
    }
    

    for the second again you shouldn't try to use boundaries Fixed code:

    #include <stdio.h>
    
    int main()
    {
    int i, j, a[5][5];
    
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
            a[i][j] = j;
        }
    }
    
    
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
            printf(" %d", a[i][j]);
        }
    printf("\n");
    }
    
    return 0;
    }