原文: https://www.programiz.com/cpp-programming/pointers-arrays
在本文中,您将了解数组与指针之间的关系,并在程序中有效地使用它们。
指针是保存地址的变量。 指针不仅可以存储单个变量的地址,还可以存储数组的单元格的地址。
考虑以下示例:
int* ptr;int a[5];ptr = &a[2]; // &a[2] is the address of third element of a[5].

假设指针需要指向数组的第四个元素,即在上述情况下的第四个数组元素的保存地址。
由于在以上示例中ptr指向第三元素,所以ptr + 1将指向第四元素。
您可能会认为ptr + 1为您提供了ptr的下一个字节的地址。 但这是不正确的。
这是因为指针ptr是指向int的指针,并且int的大小对于操作系统是固定的(int的大小是 64 位操作系统的 4 字节)。 因此,ptr和ptr + 1之间的地址相差 4 个字节。
如果指针ptr是指向char的指针,则ptr和ptr + 1之间的地址将相差 1 个字节,因为字符的大小为 1 个字节。
示例 1:C++ 指针和数组
C++ 程序,使用数组和指针显示数组元素的地址
#include <iostream>using namespace std;int main(){float arr[5];float *ptr;cout << "Displaying address using arrays: " << endl;for (int i = 0; i < 5; ++i){cout << "&arr[" << i << "] = " << &arr[i] << endl;}// ptr = &arr[0]ptr = arr;cout<<"\nDisplaying address using pointers: "<< endl;for (int i = 0; i < 5; ++i){cout << "ptr + " << i << " = "<< ptr + i << endl;}return 0;}
输出
Displaying address using arrays:&arr[0] = 0x7fff5fbff880&arr[1] = 0x7fff5fbff884&arr[2] = 0x7fff5fbff888&arr[3] = 0x7fff5fbff88c&arr[4] = 0x7fff5fbff890Displaying address using pointers:ptr + 0 = 0x7fff5fbff880ptr + 1 = 0x7fff5fbff884ptr + 2 = 0x7fff5fbff888ptr + 3 = 0x7fff5fbff88cptr + 4 = 0x7fff5fbff890
在上面的程序中,不同的指针ptr用于显示数组元素arr的地址。
但是,可以使用相同的数组名称arr使用指针符号访问数组元素。 例如:
int arr[3];&arr[0] is equivalent to arr&arr[1] is equivalent to arr + 1&arr[2] is equivalen to arr + 2
示例 2:指针和数组
C++ 程序,用于使用指针符号显示数组元素的地址。
#include <iostream>using namespace std;int main() {float arr[5];cout<<"Displaying address using pointers notation: "<< endl;for (int i = 0; i < 5; ++i) {cout << arr + i <<endl;}return 0;}
输出
Displaying address using pointers notation:0x7fff5fbff8a00x7fff5fbff8a40x7fff5fbff8a80x7fff5fbff8ac0x7fff5fbff8b0
您知道,指针ptr保存地址,表达式*ptr给出存储在地址中的值。
同样,您可以使用*(ptr + 1)获取存储在指针ptr + 1中的值。
请考虑以下代码:
int ptr[5] = {3, 4, 5, 5, 3};
&ptr[0]等于ptr,*ptr等于ptr[0]&ptr[1]等于ptr + 1,*(ptr + 1)等于ptr[1]&ptr[2]等于ptr + 2,*(ptr + 2)等于ptr[2]&ptr[i]等于ptr + i,*(ptr + i)等于ptr[i]
示例 3:C++ 指针和数组
C++ 程序,用于插入和显示使用指针符号输入的数据。
#include <iostream>using namespace std;int main() {float arr[5];// Inserting data using pointer notationcout << "Enter 5 numbers: ";for (int i = 0; i < 5; ++i) {cin >> *(arr + i) ;}// Displaying data using pointer notationcout << "Displaying data: " << endl;for (int i = 0; i < 5; ++i) {cout << *(arr + i) << endl ;}return 0;}
输出
Enter 5 numbers: 2.53.54.552Displaying data:2.53.54.552
