C++ Pointers vs Arrays

C++ Pointers

Pointers and arrays are closely related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer to the beginning of an array can access the array by using pointer arithmetic or array indexing. Consider the following program:

Example

#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // Address of array in pointer ptr = var; for (int i = 0; i < MAX; i++) { cout << "var[" << i << "the memory address of ] is"; cout << ptr << endl; cout << "var[" << i << "the value of ] is"; cout << *ptr << endl; // Move to the next position ptr++; } return 0; }

When the above code is compiled and executed, it produces the following results:

var[0]的内存地址为 0x7fff59707adc
var[0] 的值为 10
var[1]的内存地址为 0x7fff59707ae0
var[1] 的值为 100
var[2]的内存地址为 0x7fff59707ae4
var[2] 的值为 200

However, pointers and arrays are not completely interchangeable. For example, consider the following program:

Example

#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; // This is correct syntax var++; // This is incorrect } return 0; }

:

Since an array name corresponds to a pointer constant, as long as the array's value is not changed, pointer-form expressions can still be used. For example, the following is a valid statement that assigns 500 to var

*(var + 2) = 500;

The above statement is valid and compiles successfully because var has not been changed.

C++ Pointers

other extensions