 # C++ Pointers and Arrays

« Previous Tutorial Next Tutorial »

Arrays and pointers are very closely linked. In most context, C++ treats the name of an array as if it were a pointer i.e., memory address of some element. C++ interprets an array name as the address of its first element. That is, if age is an int array to hold 10 integers then age stores the address of age, the first element of the array i.e., the array name age is a pointer to an integer which is the first element of an array age.

Consider the following code fragment :

```int *a;       // a is a pointer to an integer
int age;  // age is an array holding 10 integers
cout<<"Enter values for array age\n";
for(int i=0; i<10; i++)
a = age;        // make a point to the location where age points to.
// remember age is a pointer pointing to age

// check whether both *a and *age are the same or not.
cout<<"\n a points to "<<*a<<"\n";
cout<<"age points to "<<*age<<"\n";
:```

In the above given code a is pointer to integer and age is an array holding 10 integers. The pointer a is made to point to where age is pointing to. When the data values of these pointers are printed, both the values come out to be the same. Suppose the element of age are 11 as age, 7 as age, 19 as age, 24 as age, and 17 as age.

Then the output produced by the above code would be as shown below :

```a points to 11
age points to 11```

Thus from the above given code, it is proved that the name of an array is actually a pointer that points to the first element of the array.

Since name of an array is a pointer to its first element, the arrayname + 1 gives the address of the second element of the array, arrayname + 2 gives the address of the third element, and so forth.

Thus, to print the data value of the fourth element of array age, we can give either of the following :

`cout << age ;`

or,

`cout << ∗(age + 3) ;`

## C++ Array of Pointers

Pointers also, may be arrayed like any other data type. To declare an array holding 10 int pointers, the declaration would be as follows :

`int *ip;       // array of 10 int pointers`

After this declaration, contiguous memory (remember, array elements are allocated contiguous memory locations) would be allocated for 10 pointers that can point to integers.

Now each of the pointers, the elements of pointer array, may be initialized. To assign the address of an integer variable amt to the forth element of the pointer array, we'll write

`ip = &amt;`

Now to find the value of amt, we'll write

`∗ip`

Similarly, assuming that all pointers in the array of pointers are pointing to a legal location, you can access the contents they are pointing to, using the following code :

```for(i=0; i<10; i++)
{
cout<<*ip[i]<<endl;
}```

### C++ Array of Pointers Example

Let's take a look at this C++ example program for the complete understanding on this concept.

```/* C++ Pointers and Arrays. This C++ program
* demonstrates the concept of close association
* between arrays and pointers in C++. */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int *iptr;
int fa=65, fb=66, fc=67, fd=68, fe=69;
int i;

// initialize array pointers by making them point to 5 different ints
iptr = &fa;
iptr = &fb;
iptr = &fc;
iptr = &fd;
iptr = &fe;

// now prints the values being pointed to by the pointers
for(i=0; i<5; i++)
{
cout<<"The pointer iptr["<<i<<"] points to "<<*iptr[i]<<"\n";
}
cout<<"\n";

// now print the addresses stored in the array
cout<<"The base address of the array iptr of pointers is "<<iptr<<"\n";
for(i=0; i<5; i++)
{
cout<<"The address stored in iptr["<<i<<"] is "<<iptr[i]<<"\n";
}

getch();
}```

Here is the sample run of the above C++ program

Let's take a deep look at this C++ program for the complete understanding on the address manipulation in two dimensional array in C++

```/* C++ Pointers and Arrays. This C++ program
* also demonstrates the same concept as the
* above C++ program shows, but this program
* demonstrates the address manipulation in
* two dimensional array in C++ */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int arr = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} };
int *iptr = &arr;

cout<<"1.  *(*(arr+2)+1)\t = "<<*(*(arr+2)+1)<<"\n";
cout<<"2.  *(*arr+2)+5\t\t = "<<*(*arr+2)+5<<"\n";
cout<<"3.  *(*(arr+1))\t\t = "<<*(*(arr+1))<<"\n";
cout<<"4.  *(*(arr)+2)+1\t = "<<*(*(arr)+2)+1<<"\n";
cout<<"5.  *(*(arr+1)+3)\t = "<<*(*(arr+1)+3)<<"\n";
cout<<"6.  *iptr\t\t = "<<*iptr<<"\n";
cout<<"7.  *(iptr+2)\t\t = "<<*(iptr+2)<<"\n";
cout<<"8.  (*(iptr+3)+1)\t = "<<(*(iptr+3)+1)<<"\n";
cout<<"9.  *(iptr+5)+1\t\t = "<<*(iptr+5)+1<<"\n";
cout<<"10. ++*iptr\t\t = "<<++*iptr<<"\n";

getch();
}```

Below is the sample run of the above C++ program:

## C++ Pointers and Strings

As you know that C++ treats a string as an array of characters, we are discussing the strings under arrays. A string is a one-dimensional array of characters terminated by a null ('\0'). You have learnt to work with strings in class XI. To print a string with ... in between adjacent letters, you will probably use the following code fragment :

```char name[] = "POINTER" ;       // declare a string
for(int i = 0; name[i] != '\0' ; i++)
{
cout << "..." << name[i] ;
}```

Alternatively, the same can be achieved using a character pointer also. Consider the following code fragment :

```char name[] = "POINTER" ;
char ∗cp ;         // a char pointer
for(cp = name ; ∗cp != '\0' ; cp++)
{
cout << "..." << ∗cp ;
}```

But the above given code segments produce the same output. That is,

`...P...O...I...N...T...E...R`

You are familiar with the first code segment. In the second one, the for loop in the initialization section makes cp (the char pointer) point to name (the string) and then prints the data value being pointer to by cp in each cycle of for. At the end of each cycle, the cp is incremented so that it points to the next character in the string. The loop continues as long as the cp is not pointing to null ('\0'). To print the entire string in the same line using the pointer, the loop will be as

```for(cp = name ; ∗cp != '\0' ; cp++)
{
cout << ∗cp ;
}
cout << "\n" ;```

Thus, we have seen how we can access strings and their constituent characters using char pointers. We are also familiar with array of pointers. An array of char pointers is very popularly used for storing several strings in memory. Let's see how several strings can be stored in the array of pointers;

`char ∗names[] = {"Sachin", "Dhoni", "Sehwag", "Yuvraj", "Raina"} ;`

In the above given declaration names[] is an array of char pointers whose element pointers contains base address of respective names. That is, the element pointer names stores the base address of string "Sachin", the element pointer names stores the above address of string "Dhoni", and so forth.

The array of char pointers is generally preferred over two dimensional array of characters. There are two reasons behind this, which are :

• An array of pointers makes more efficient use of available memory by consuming lesser number of bytes to store the strings.
• An array of pointers makes the manipulation of the strings much easier. One can easily exchange the positions of strings in the array using pointers without actually touching their memory locations.

### C++ Pointers and Strings Example

Let's take a look at this C++ example program for the complete understanding on this concept.

```/* C++ Pointers and Arrays. Pointers and Strings */

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char *names[] = {"Sachin", "Dhoni", "Sehwag", "Raina", "Yuvraj"};
int len=0;
len=strlen(names);   // length of 2nd string
cout<<"Originally:\n\tstring 2 is ";
cout.write(names,len).put('\n');
cout<<"\tand string 4 is ";
cout.write(names,len).put('\n');

// now exchange the position of string 2 and 4
char *tptr;
tptr = names;
names = names;
names = tptr;

// now print the exchanged string
cout<<"\nExchanged:\n\tstring 2 is ";
cout.write(names,len).put('\n');
cout<<"\tand string 4 is ";
cout.write(names,len).put('\n');

getch();
}```

Here is the sample output of the above C++ program

C++ Online Test

« Previous Tutorial Next Tutorial »