0

int main()
{
    int arr[3][3] = {1,2,3,4,5,6,7,8,9};
    int j;
    for(int i = 0; i<3; i++){
        printf("%d",arr[i+1][j+1]);
    }
    return 0;
}

output - 580 Does the output depends on the compiler? why the auto variable j defaults to 0? what happens if j contains a garbage value if it doesn't default to zero? What will be the output then?

  • 1
    Undefined behaviour. An unitialized auto variable may contain any value. If it contains 0 is because of the way your compiler implemented it, or the way your SO initializes memory for your stack/program/data area – mcleod_ideafix Jul 01 '20 at 14:01
  • @hnefatl In C "auto" means "automatic storage", not "automatic type inferred". auto in fact is a reserved word in C, even it's rarely used. – mcleod_ideafix Jul 01 '20 at 14:03
  • First thing that you might get a SEG fault because you are trying to access arr[3][j + 1]. It depends on the compiler but if it's a garbage value you might be left with SEG fault – Sai Sreenivas Jul 01 '20 at 14:03
  • 1
    @Sai: There is no "should" get a seg-fault. The program *might* seg-fault, or might run producing garbage output. Seg-fault is not required and not guaranteed. In general, you'll find you can go a little-bit past most arrays without an error, just getting unpredictable values. – abelenky Jul 01 '20 at 14:05

1 Answers1

2

You are right that j is not initialized, and therefore might have any value in it. It apparently happens to have 0 in your test run, but that is not guaranteed at all.

If j has some other non-zero "garbage" value, the output could be anything at all, including a program crash.

abelenky
  • 63,815
  • 23
  • 109
  • 159