C ++程序使用指针访问数组的元素
指针存储变量的存储位置或地址。换句话说,指针引用一个存储位置,并且获取存储在该存储位置的值称为取消引用指针。
给出了使用指针访问数组的单个元素的程序,如下所示:
示例
#include <iostream>
using namespace std;
int main() {
int arr[5] = {5, 2, 9, 4, 1};
int *ptr = &arr[2];
cout<<"The value in the second index of the array is: "<< *ptr;
return 0;
}输出结果
The value in the second index of the array is: 9
在上面的程序中,指针ptr将元素的地址存储在数组的第三个索引处,即9。
在下面的代码片段中显示了这一点。
int *ptr = &arr[2];
指针被取消引用,并使用间接(*)运算符显示值9。这证明如下。
cout<<"The value in the second index of the array is: "<< *ptr;
给出了另一个使用单个指针访问数组的所有元素的程序,如下所示。
示例
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = &arr[0];
cout<<"The values in the array are: ";
for(int i = 0; i < 5; i++) {
cout<< *ptr <<" ";
ptr++;
}
return 0;
}输出结果
The values in the array are: 1 2 3 4 5
在上面的程序中,指针ptr存储数组的第一个元素的地址。这样做如下。
int *ptr = &arr[0];
此后,使用for循环取消引用指针并打印数组中的所有元素。指针在循环的每次迭代中递增,即在每次循环迭代中,指针指向数组的下一个元素。然后打印该数组值。在下面的代码片段中可以看到。
for(int i = 0; i < 5; i++) {
cout<< *ptr <<" ";
ptr++;
}热门推荐
10 对别人新年祝福语简短
11 广东新居入伙简短祝福语
12 讲课祝福语简短10字
13 小红书生日祝福语简短
14 简短中秋祝福语朋友结婚
15 祝福语简短唯美10字
16 猪年元旦祝福语简短创意
17 撩妹生日祝福语简短
18 求助短信生日祝福语简短