跳到主要内容

C++ 编程:使用指针访问数组元素

要理解这个例子,你需要掌握以下 C++编程 主题的知识:

示例:使用指针访问数组元素

#include <iostream>
using namespace std;

int main()
{
int data[5];
cout << "Enter elements: ";

for(int i = 0; i < 5; ++i)
cin >> data[i];

cout << "You entered: ";
for(int i = 0; i < 5; ++i)
cout << endl << *(data + i);

return 0;
}

输出

Enter elements: 1
2
3
5
4
You entered: 1
2
3
5
4

在这个程序中,用户输入的五个元素被存储在整数数组 data 中。

然后,使用for循环访问 data 数组,并将数组中的每个元素打印到屏幕上。

访问此页面了解更多关于 指针与数组的关系