C ++ pointers vs array
Pointers and arrays are closely related. In fact, pointers and arrays in many cases are interchangeable. For example, a pointer to the beginning of the array, the array can be accessed by using pointer arithmetic or array index. Consider the following program:
#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // 指针中的数组地址 ptr = var; for (int i = 0; i < MAX; i++) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // 移动到下一个位置 ptr++; } return 0; }
When the above code is compiled and executed, it produces the following results:
Address of var[0] = 0xbfa088b0 Value of var[0] = 10 Address of var[1] = 0xbfa088b4 Value of var[1] = 100 Address of var[2] = 0xbfa088b8 Value of var[2] = 200
However, pointers and arrays are not completely interchangeable. For example, consider the following program:
#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; for (int i = 0; i < MAX; i++) { *var = i; // 这是正确的语法 var++; // 这是不正确的 } return 0; }
Pointer operator * is applied to the var is perfectly acceptable, but the modification var value is illegal. This is because var is a pointer to the beginning of the array constant, it can not serve as the left value.
Because an array name corresponds to a pointer constant, they do not change the value of the array, you can still use the pointer form of expression. For example, the following is a valid statement, the var [2] 500 assignment:
*(var + 2) = 500;
The above statement is valid, and can successfully compile, because var unchanged.