c语言

c语言怎么读取数组中的数

小亿
222
2023-09-14 01:28:37
栏目: 编程语言

在C语言中,可以使用循环结构(例如for循环或while循环)来依次读取数组中的元素。下面是两种常用的方法:

  1. 使用下标访问数组元素:
#include <stdio.h>
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]来访问数组中的元素。

  1. 使用指针访问数组元素:
#include <stdio.h>
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可以控制指针的偏移量,从而访问数组中的不同元素。

0
看了该问题的人还看了