C++ Pointer to an Array

C++ Arrays

You can skip this chapter for now, and come back to study its contents after understanding the concept of C++ pointers.

If you have some understanding of C++ pointers, then you can start studying this chapter. The array name is a constant pointer to the first element in the array. Therefore, in the following declaration:

double exampleAarray[50];

exampleAarrayis a pointer to &exampleAarraypassign toexampleAarraythe address of the first element:

double *p;
double exampleAarray[10];

p = exampleAarray;

.

Once you store the address of the first element in p, you can use *p, *(p+1), *(p+2), etc. to access array elements. The following example demonstrates these concepts discussed above:

Example

#include <iostream> using namespace std; int main () { // double array with 5 elements double exampleAarray[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double *p; p = exampleAarray; // output the value of each element in the array cout << "Array values using pointers" << endl; for ( int i = 0; i < 5; i++ ) { cout << "*(p + " << i << ") : "; cout << *(p + i) << endl; } cout << "Use exampleAarray as the address of the array value" << endl; for ( int i = 0; i < 5; i++ ) { cout << "*(exampleAarray + " << i << ") : "; cout << *(exampleAarray + i) << endl; } return 0; }

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

使用指针的数组值 
*(p + 0) : 1000
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
使用 exampleAarray 作为地址的数组值 
*(exampleAarray + 0) : 1000
*(exampleAarray + 1) : 2
*(exampleAarray + 2) : 3.4
*(exampleAarray + 3) : 17
*(exampleAarray + 4) : 50

In the above example, p is a pointer to double, which means it can store a variable of type double. Once we have the address in p,*pwill give the value stored at the corresponding address in p, as demonstrated in the example above.

C++ Arrays

other extensions