I did not understand the output. Why I am getting the garbage value?

Viewed 58
#include<stdio.h>
#include<conio.h>
int main() {
    int a[2][3]={0},i,j;

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

OUTPUT:

000
000
026886320
  1. I understood 000 000 output but, I did not expecting garbage value 026886320 etc it changes every time i run the code.
  2. what is the solution to remove/avoid garbage value?
3 Answers

Try i < 2 in your first for loop since a only has 2 elements.

The output differs every time since you're trying to read a[2] which points to memory that is not allocated to your array.

By doing for (i=0; i<3; i++) you are accessing an area of memory that is out of the boundaries of your 2-dimensional array, therefore you get gabrage data that is just random bits that are saved in that part of the program's memory. That's also why you get different values on every execution of your code.

Try doing for (i=0; i<2; i++)

when you enter the value for an array a[3] you are asking compiler to work from 0-2, as array starts from 0 and works till it has elements, like a has 3 elements, so array will work like this a[0] = 1; a[1] =2; a[2] =3; and this is happening in case of your code, for is working to find arrays till a[3] and this makes it access out of bounds memory which shows a garbage value while loop is still working, but the array has elements stored till a[2]. Thanks!

Related