POINTERS in C++

Introduction:

Welcome to the 7th tutorial in the series of Short Tutorial on C++ for beginners. We have discussed arrays and strings in the previous tutorial. Now is the time to discuss something more advanced and technical. Yes, we are going to discuss pointers in this tutorial. Pointers are considered one of the trickiest concepts in the C++ programming. But don’t worry; we are going to explain it in a very lucid manner. I can assure that after completing this tutorial, you will be teaching pointers to your fellows around.

As usual we will start with our basic console application which will look like the following code.

#include <iostream>

using namespace std;

int main()

{

	//code here

return 0;

}

 

Let’s have a quick glance at the contents:

 

Table of Contents:

What is a pointer?

Benefits of using pointers

Character Pointers

 

Pointer Arrays

1- Single Dimensional pointer arrays

2- Multidimensional pointer arrays

1- Pointer Arithmetic

2- Pointer to character strings

 

What is a pointer?

This question is asked by every newbie C++ programmer and starters get confused about this topic. However this topic is not as difficulty as it has been blamed. Pointer is just like a variable. Difference is in the syntax and what a pointer can store. A variable stores a value. For example if you declare a variable of type integer and stores a value “4” in it. It will store the value 4 in the memory location for variable you declared. On the other hand pointers are used to store the memory address of some variable. It means that memory allocated to pointer contains the memory address of some other variable and not the actual value of that variable. Here is how we declare a pointer.

	int * pointer1;

 

You can see that only difference between declaring a variable and pointer is that asterisk before the name of the variable. Now if you want to refer to the memory address of a variable you will use pointer as follows:

	*pointer1 = somevariable;

 

*pointer1 will refer to the variable stored by the variable. In case you want to refer to the memory address of a variable you will simply use the name of the pointer as “pointer1”.

Following example explains this concept.

Example 1:


	int * pointer1;

	int variable1 = 50;

	pointer1 = &variable1;

	cout << variable1 << endl;

	*pointer1 = 100;

	cout<<variable1;

Output:

In this example, we have initialized variable1 with value 50. Then we have assigned the memory address of variable one to pointer one in the third line. Now both variable1 and pointer1 points to same memory location. After that we printed the value of variable 1. We then assign value of 100 to that memory address using pointer and then when we print out the value of variable1, it has changed to 100 because pointer1 has changed the value stored in that memory address.

Benefits of Using Pointers

The Following are some of the advantages that pointers provide to developers:

* Size of the array cannot be dynamically allocated in C++; however using pointers we can decide the size of the array at run time execution.

* Functions or methods can only return single value during one function call. Using pointers we can modify values of several memory locations in one function which is virtually equivalent to returning multiple values using one function call.

* Various data structures, such as linked list and trees are developed using pointers as they enables the programmer to access memory address which are used to link nodes in linked lists and trees.

* Pointers are particularly useful in low level programming such as writing reference counts for garbage collectors.

* Pointers can also be used for data sharing among different sections of code. As memory address can be accessed from anywhere. They can be used as global variables.

* Pointers can be used to pass address of an object to a function instead of passing the whole object itself. This type of passing is called passing by reference in programming terminology.

An example showing how memory can be dynamically allocated and freed using special key words “New” and “Delete” is as follows. Pointers are used to refer to these dynamic memory locations as shown in following example:

Example 2:


int * pointer1 = NULL;

// Here the pointer is initially referring to null memory location.

pointer1 = new int;

// Memory to hold integer type has been dynamically allocated using "new" key word.

*pointer1= 150; // Value has been stored in dynamically allocated memory address.

cout <<"Dynamically allocated value is :"<< *pointer1 << endl;

delete pointer1; // Memory has been emptied using delete key word

cout <<"Value after free memory location: "<< *pointer1;

// prints a negative value showing memory location is null

Output:

 

Character Pointers:

As discussed earlier, a pointer can hold any data type. Same is the case with characters and strings. Pointer can refer to memory address of any string or character. In fact pointer gives you more control over your strings by individual, array index style reference to each character of a string. Following example explains this concept.

Example 3:


char * pointer1;

pointer1 = "TBYtutorials";

cout << pointer1 <<endl;

cout << pointer1[0]<<endl;

cout << pointer1[1]<<endl;

pointer1++;

cout << pointer1<<endl;

char abc[]= "TBYtutorials";

// abc ++ not possible

Output:

 

We used a pointer to point it towards a character string. Notice we can access the individual elements of the character string using the similar array style index referring. But there is a difference between ordinary character string and pointer to character string. Ordinary character string is constant and cannot be incremented like pointer. Pointer simply points to the first memory location of the character string and prints the whole string if outputted. In case we increment a pointer with ++ as the case in above example, pointer now points to the index next to the first index hence the output string starts from the second character as “BYtutorials” in the above example. On the other hand ++ operator cannot be applied to constant string “abc” in the above example.

 

POINTER ARRAYS:

The concept of pointer arrays is very similar to a basic pointer. Declaring pointer arrays is similar to declaring a basic pointer. Following example explains this concept. Storing and retrieving values also has the same technique of using “*” and “&” but with the array index.

1- Single Dimensional Pointer Arrays:

Example 4:


int abc [4] = {10, 41, 32, 15};

int *pointerarray [4];

for (int i = 0; i < 4; i++)

{

	pointerarray[i] = &abc[i]; // store values in pointer array

}

for (int i = 0; i < 4; i++)

{

	cout << *pointerarray[i]<<endl ; // print values using pointer array

}

Output:

 

2- Multi-Dimensional Pointer Arrays:

Example 5:


int abc [4][4] = {

	{10, 41, 32, 15},

	{48, 13, 49, 75},

	{74, 95, 35, 16},

	{16, 74, 63, 34}

};

int *pointerarray [4][4];

for (int i = 0; i < 4; i++)

{

	for (int j=0; j<4; j++)

	pointerarray[i][j] = &abc[i][j]; // store values in pointer array

}

for (int i = 0; i < 4; i++)

{

	for (int j=0; j<4; j++)

		cout << *pointerarray[i][j]<<" "; // print values using pointer array

		cout << endl;

}

 

Output:

 

PROJECTS:

1- Pointer Arithmetic:

As discussed earlier, pointers point to the memory address of a variable. We can perform arithmetic functions on these pointers to manipulate the memory address to which they are pointing. In the project that follows we have used an array and then assign the address of the array to pointer. We will then apply arithmetic operators to the pointers and see the results.

Code:


#include <iostream>

using namespace std;

int main()

{

	int abc [6] = {1,52,47,36,26,95};

	int * pointer1 = abc;

	cout << "Pointer Address = " <<pointer1 << " Pointer Value = "<<*pointer1<<endl;

	pointer1++;

	cout << "Pointer Address = " <<pointer1 << " Pointer Value = "<<*pointer1<<endl;

	pointer1 = pointer1 + 3;

	cout << "Pointer Address = " <<pointer1 << " Pointer Value = "<<*pointer1<<endl;

	pointer1 = pointer1--;

	cout << "Pointer Address = " <<pointer1 << " Pointer Value = "<<*pointer1<<endl;

	pointer1 = pointer1 - 3;

	cout << "Pointer Address = " <<pointer1 << " Pointer Value = "<<*pointer1<<endl;

	pointer1++;

	int * pointer2 = abc;

	if(pointer1 > pointer2)

		cout<<"Pointer 1 is greater than 2";

		getchar();// Just to prevent screen from disappearing

		cin.get();// Just to prevent screen from disappearing

}

In this code, we have initialized the pointer with the memory address of the array. Initially pointer points to the first memory address and the value stored will be 1. After that we incremented the pointer by one. Now, since the pointer is of type “int” which is of four byte, after incrementing the pointer it will point to memory address which is four bytes greater than previous memory address and it will contain the next array value which is 52, since arrays store data in contiguous memory locations. Similarly incrementing the pointer by three will take the pointer to refer to memory location of current location plus 12 bytes since 3 integers takes 12 bytes and it will point to new value which is 26. Exactly same is the case with subtraction and decrement of pointers. In the same way two pointers can be compared using “<” “>” or “==” based on their memory address as shown in the last lines of code. Following is the output of the above code.

Output:

 

2- Pointer to character Strings:

As discussed earlier, there is a difference between a constant character string declared using

char abc[] and a pointer to string such as char *ptr;

Although both can store strings but in case of costant char abc it holds the actual data of string in the form of individual characters in contiguous array index. On the other hand char *ptr points to the starting address of the array and we can continuously move to the next memory address using the pointer arithmetic. Following project explains this concept. In this example pointer is moving consistently to the next memory location of the string and hence the output string starts printing with the value stored at that index. The code and output of the projects are as follows:

Code:


#include <iostream>

using namespace std;

int main()

{

	char *ptr = "Welcome to TBY tutorials";

	for (int i=0; i<24; i++)

	{

		cout <<ptr<<endl;

		ptr++;

	}

	getchar();// Just to prevent screen from disappearing

	cin.get();// Just to prevent screen from disappearing

}

 

Output:

 

You might want to read…

C++ for Beginners Part 8 – Functions

C++ for Beginners Part 7 – Pointers

C++ for beginners Part 6 – Arrays & Strings

C++ for beginners Part 5 – “switch and loops”

C++ for beginners Part 4 – else if Statement in C++

C++ for beginners Part 3 – Conditional “if” Statement

C++ for beginners Part 2 – The Basics of C++

C++ for beginners Part 1 – Installing Visual C++ Expres

 

More C / C++ and Dev Programming Tutorials:

 

If you liked this tutorial, please share with your friends:

Leave a Reply

Your email address will not be published. Required fields are marked *