c语言如何读取数组中的数
在C语言中,可使用循环结构(例如for循环或while循环)来顺次读取数组中的元素。下面是两种经常使用的方法:
1. 使用下标访问数组元素:
```c
#include
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i;
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果为:1 2 3 4 5
这类方法使用循环变量i作为数组的下标,通过arr[i]来访问数组中的元素。
2. 使用指针访问数组元素:
```c
#include
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // 将指针ptr指向数组的首地址
int i;
for (i = 0; i < 5; i++) {
printf("%d ", *(ptr + i));
}
return 0;
}
```
输出结果与上述方法相同:1 2 3 4 5
这类方法使用指针ptr来指向数组的首地址,通过*(ptr + i)来访问数组中的元素。循环变量i可以控制指针的偏移量,从而访问数组中的区分元素。
TOP