Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C is there a pattern for variables in an array which are assigned 0 value?

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?

like image 405
Jaspal Singh Avatar asked Dec 21 '22 01:12

Jaspal Singh


2 Answers

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.

like image 183
Jacob Pollack Avatar answered May 26 '23 20:05

Jacob Pollack


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));

like image 36
Scotty Bauer Avatar answered May 26 '23 20:05

Scotty Bauer