Here are the various methods to declare an array of zero values in C language –
1. Using GCC
int myArray[512] = { [ 0 ... 511 ] = 0 };
This method works in GCC only. The benefit of using it is that you can initialize the array values to anything and not just zero.
2. Declaring array without value
int myArray[512];
If we do not provide any value during array declaration then it will automatically initialize them to 0.
3. Filling 0 in partially filled array
Suppose you have an array where some indexes are filled with values while others are not then you can use this code –
int myArray[512] = {};
4. Using memset()
memset()
is used to set the first n
number of values to c
of destination dest
–
memset(dest, c, n)
In the above memset()
definition the first parameter is dest
, second is c
and third is n
. So first n
values of dest
will become c
.
We can use this function to initialize the values of array to any character. You should use this when you want to re-initialize the array at any point in your program.
int myArray[512]; memset(myArray, 0, sizeof(myArray));