Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Pointers vs Arrays

C++ Pointers vs Arrays

C++ Pointers C++ Pointers

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

Example

#include

<

iostream

using

namespace

std

;

const

int

MAX

=

3

;

int

main

(

)

{

int

var

[

MAX

]

=

{

10

,

100

,

200

}

;

int

ptr

;

// Array address in the pointer

ptr

=

var

;

for

(

int

i

=

0

;

i

<

MAX

;

i

++

)

{

cout

<<

"

var[

"

<<

i

<<

"

] memory address is

"

;

cout

<<

ptr

<<

endl

;

cout

<<

"

var[

"

<<

i

<<

"

] value is

"

;

cout

<< *

ptr

<<

endl

;

// Move to the next position

ptr

++;

}

return

0

;

}

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



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, see the program below:

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

;

}

Applying the pointer operator * to var is perfectly fine, but modifying the value of var is illegal. This is because var is a constant pointing to the beginning of the array and cannot be used as an lvalue.

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[2]:



*(var + 2) = 500;

The statement above is valid and compiles successfully because var is unchanged.

C++ Pointers C++ Pointers