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

C++ Arrays of Pointers

C++ Arrays of Pointers

C++ Pointers C++ Pointers

Before we explain the concept of arrays of pointers, let's first look at an example that uses an array of 3 integers:

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

++

)

{

cout

<<

"

Value of var[

"

<<

i

<<

"

] =

"

;

cout

<<

var

[

i

]

<<

endl

;

}

return

0

;

}

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



Value of var[0] = 10

Value of var[1] = 100

Value of var[2] = 200

There may be a situation where we want the array to store pointers to int, char, or other data types. The following is a declaration of an array of pointers to integers:



int *ptr[MAX];

Here, declare ptr as an array consisting of MAX integer pointers. Therefore, each element in ptr is a pointer to an int value. The following example uses three integers that will be stored in an array of pointers, as shown below:

Example

#include

<

iostream

using

namespace

std

;

const

int

MAX

=

3

;

int

main

(

)

{

int

var

[

MAX

]

=

{

10

,

100

,

200

}

;

int

ptr

[

MAX

]

;

for

(

int

i

=

0

;

i

<

MAX

;

i

++

)

{

ptr

[

i

]

= &

var

[

i

]

;

// assign the address of an integer

}

for

(

int

i

=

0

;

i

<

MAX

;

i

++

)

{

cout

<<

"

Value of var[

"

<<

i

<<

"

] =

"

;

cout

<< *

ptr

[

i

]

<<

endl

;

}

return

0

;

}

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



Value of var[0] = 10

Value of var[1] = 100

Value of var[2] = 200

You can also use an array of pointers to char to store a list of strings, as follows:

Example

#include

<

iostream

using

namespace

std

;

const

int

MAX

=

4

;

int

main

(

)

{

const

char

names

[

MAX

]

=

{

"

Zara Ali

"

,

"

Hina Ali

"

,

"

Nuha Ali

"

,

"

Sara Ali

"

,

}

;

for

(

int

i

=

0

;

i

<

MAX

;

i

++

)

{

cout

<<

"

Value of names[

"

<<

i

<<

"

] =

"

;

cout

<<

names

[

i

]

<<

endl

;

}

return

0

;

}

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



Value of names[0] = Zara Ali

Value of names[1] = Hina Ali

Value of names[2] = Nuha Ali

Value of names[3] = Sara Ali

C++ Pointers C++ Pointers