In C is there a pattern for variables in an array which are assigned 0 value?
arrays, c, initialization
Solution
This behaviour is undefined and it is merely a coincidence. When you declare an array on the stack and do not initialize it then the array will take on values from another (likely the previous) stack frame.
Aside: If you wanted to zero-fill an array declared on the stack (in constant time) then you can initialize it using the following initialization syntax:
int arr[ 5 ] = { 0 };
It will write the first element as 0 and zero-fill the rest of the elements. However, if you declared an uninitialized array globally then it will automatically be zero-filled.
Problem
I want to know if an array of int elements is declared in C. Is there a pattern according to which only some values of the array are assigned to 0 while others store garbage values? Ex: ``` #include <stdio.h> void main() { int a[5]; int i; for (i=0;i<=4;i++) { printf("%d\n",a[i]); } } ``` After I compile and run the program I get this output,i.e. ``` 0 0 4195344 0 2107770384 ``` So zeroes are there in `a[0], a[1]` and `a[3]` while `a[2]` contains the same value each time compiled and run whereas `a[4]` value keeps on changing (including negative numbers). Why does this happen that only some fixed indices of an array are initialized to zero and does it have something related to past allocation of memory space?