C++ Pointers to Arrays
You can skip this chapter first and come back to study it after you understand the concept of C++ pointers.
If you have some understanding of the concept of C++ pointers, then you can start learning this chapter. An array name is a constant pointer to the first element in the array. Therefore, in the declaration below:
double runoobAarray[50];
runoobAarray is a pointer to &runoobAarray[0], that is, the address of the first element of the array runoobAarray. Therefore, the following program fragment assigns p to runoobAarray 's first element address:
double *p;
double runoobAarray[10];
p = runoobAarray;
It is legal to use the array name as a constant pointer, and vice versa. Therefore, *(runoobAarray + 4) is a legal way to access the data of runoobAarray[4].
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 example below demonstrates the concepts discussed above:
Example
#include
<
iostream
using
namespace
std;
int
main
(
)
{
// Double-precision floating-point array with 5 elements
double
runoobAarray
[
5
]
=
{
1000
.0
,
2
.0
,
3
.4
,
17
.0
,
50
.0
}
;
double
p
;
p
=
runoobAarray
;
// output the value of each element in the array
cout
<<
"
Array values using pointer
"
<<
endl
;
for
(
int
i
=
0
;
i
<
5
;
i
++
)
{
cout
<<
"
*(p +
"
<<
i
<<
"
) :
"
;
cout
<< *
(
p
i
)
<<
endl
;
}
cout
<<
"
Array values using runoobAarray as address
"
<<
endl
;
for
(
int
i
=
0
;
i
<
5
;
i
++
)
{
cout
<<
"
*(runoobAarray +
"
<<
i
<<
"
) :
"
;
cout
<< *
(
runoobAarray
i
)
<<
endl
;
}
return
0
;
}
When the code above is compiled and executed, it produces the following result:
使用指针的数组值
*(p + 0) : 1000
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
使用 runoobAarray 作为地址的数组值
*(runoobAarray + 0) : 1000
*(runoobAarray + 1) : 2
*(runoobAarray + 2) : 3.4
*(runoobAarray + 3) : 17
*(runoobAarray + 4) : 50
In the example above, p is a pointer to double, which means it can store a variable of type double. Once we have the address in p, *p will give the value stored at the corresponding address in p, as demonstrated in the example above.
C++ Arrays