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?
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.
In C, when you declare your array that way it will not initialize the array. That's all garbage data. It's luck that there are zeros.
If you want to init the array to 0 use
memset(a,0,sizeof(a));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With