After Declaration Array Initialization
If you need to initialize an array to zero after it has been declared, you can use a loop or the memset()
function from the C standard library.
// C program to initialize an array to zero after
// declaration
#include <stdio.h>
#include <string.h>
int main()
{
int arr[5];
// Using a loop
for (int i = 0; i < 5; i++) {
arr[i] = 0;
}
// Using memset()
memset(arr, 0, sizeof(arr));
// Print the array
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output
0 0 0 0 0
How to Initialize Array to 0 in C?
Initializing an array to zero is a common practice in programming to ensure that all elements start with a known value. In C, there are several ways to initialize an array to zero. In this article, we will explore different methods to do so.