In C language, how do I Initialize an array to 0 ?, Array Initialization
How to initialize the array to 0?
Statement for declaring arrays in C language:
int arr[100];
In this way, the declared array stores random unknown data, which is garbage for users. In many cases, we need to initialize the array to zero to perform other operations.
The simplest way is to use a loop bar array to set all elements to 0:
int arr[100];int i = 0;for(i = 0 ; i < 100 ; i++) arr[i] = 0; //This will make all ZERO
We can also use other methods to initialize the array to 0:
1,Global variables and static variables are automatically set to 0 during initialization. If we declare a global variable, it will be changed to 0 before running.
int arr[1024]; // This is globalint main(void){ //statements}
2,For partial arrays, we also have the abbreviated initialization syntax. If an array is partially initialized, the uninitialized elements are automatically set to 0 of the corresponding type. This is automatically completed by the compiler. You can write as follows:
int main(void){ int arr[1024] = {0}; // This will make all ZERO // statements}
Variable-length array (flexible array) is not available.
3,You can also use the memset function to initialize the array at the beginning of the program. This command is particularly useful after you have modified the array and want to reset it to all 0. (Applicable to variable-length arrays)
Header file: # include
int arr[1024];arr[5] = 67;memset(ZEROARRAY, 0, 1024); //This will reinitialize all to ZERO