Site icon Study Algorithms

How to initialize an array to 0 in C ?

In C, we declare an array as:-

int arr[100];

But by simply doing this declaration, the array is assigned all junk values. There can be many cases and situations when we need to initialize all the elements to ZERO (0) before we can make any further computations.

The most naive technique to initialize is to loop through all the elements and make them 0.

int arr[100];
int i = 0;
for(i = 0 ; i < 100 ; i++)
    arr[i] = 0;  //This will make all ZERO

We have 3 other simple techniques as:-
1.>  Global variables and static variables are automatically initialized to zero. If we have an array at global scope it will be all zeros at runtime.

int arr[1024]; // This is global
int main(void)
{
    //statements
}

2.> There is also a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. The compiler would fill the unwritten entries with zeros. You could write:

int main(void)
{
    int arr[1024] = {0};  // This will make all ZERO
    // statements
}

3.> Alternatively you could use memset to initialize the array at program startup. This command is particularly useful if you had changed it and wanted to reset it back to all zeros.

int arr[1024];
arr[5] = 67;
memset(ZEROARRAY, 0, 1024); //This will reinitialize all to ZERO
Exit mobile version