How to iterate through an array in the C language?
In C language, loop structures can be used to iterate through arrays. Here are two commonly used methods for iterating over arrays.
- Traverse the array using a for loop.
int main() {
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]); // 计算数组长度
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
return 0;
}
- Traverse the array using pointers.
int main() {
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]); // 计算数组长度
int *ptr = arr; // 定义指向数组的指针
for (int i = 0; i < length; i++) {
printf("%d ", *(ptr + i));
}
return 0;
}
It is important to pay attention to the boundary conditions of the array when using any traversal method to prevent accessing out of bounds.