在C语言中,可以使用循环结构(例如for循环或while循环)来依次读取数组中的元素。下面是两种常用的方法:
- 使用下标访问数组元素:
#includeint 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]来访问数组中的元素。
- 使用指针访问数组元素:
#includeint 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可以控制指针的偏移量,从而访问数组中的不同元素。