How to initialize an array to all zeros in the C language
You can use a loop statement to assign all elements of an array to 0.
Option 1:
Method 1: Use a for loop to iterate through the array and assign each element to be 0 one by one.
#include <stdio.h>
int main() {
int arr[5]; // 声明一个包含5个元素的整型数组
// 使用for循环遍历数组,将每个元素赋值为0
for (int i = 0; i < 5; i++) {
arr[i] = 0;
}
// 打印数组的值
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Option 2: Use the memset function to assign all elements of the array to 0.
#include <stdio.h>
#include <string.h>
int main() {
int arr[5]; // 声明一个包含5个元素的整型数组
// 使用memset函数将数组的所有元素赋值为0
memset(arr, 0, sizeof(arr));
// 打印数组的值
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Both methods can be used to assign all elements of an array to 0. The first method uses a for loop to assign each element one by one, while the second method uses the memset function to set the entire memory block of the array to 0.