Home > Article > Backend Development > How are pointers and arrays related in C++?
Pointers and arrays are closely related in C++: pointers store variable addresses, while arrays are essentially collections of contiguous memory cells. The array name is a constant pointer pointing to the first element of the array. Pointer arithmetic can be used to iterate over array elements, similar to using array indexing.
The connection between pointers and arrays in C++
In C++, pointers and arrays are closely related, becausearrays Essentially a collection of contiguous memory cells, and pointers store the addresses pointing to these memory cells.
Pointer
Array
The relationship between pointers and arrays
Practical case
Consider the following C++ code:
int main() { int arr[] = {1, 2, 3, 4, 5}; int *ptr = arr; // ptr 指向 arr cout << "Using pointer:" << endl; for (int i = 0; i < 5; i++) cout << *ptr++ << " "; // 使用指针运算器访问元素 cout << "\nUsing array index:" << endl; for (int i = 0; i < 5; i++) cout << arr[i] << " "; return 0; }
This code demonstrates the use of pointers and array indexes to access array elements, output As follows:
Using pointer: 1 2 3 4 5 Using array index: 1 2 3 4 5
The above is the detailed content of How are pointers and arrays related in C++?. For more information, please follow other related articles on the PHP Chinese website!