Welcome to the 7th tutorial in the series. 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 you that after completing this tutorial, you will be teaching pointers to all your friends!
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 it is not as difficult as it seems. A pointer is just like a variable. The difference is in the syntax and what a pointer can store. For example, a variable stores a value. On the other hand, pointers are used to store the memory address of some variable. It means that memory allocated to a pointer contains the memory address of some other variable and not the actual value of that variable.
Here is how we declare a pointer of type integer.
int * pointer1;
You can see that the only difference between declaring a variable and a pointer is that asterisk before the name of the pointer. Now if you want to refer to the memory address of a variable named variable1 you need to add the & character in front and use the name of the pointer as “pointer1” as follows:
pointer1 = &variable1;
Now pointer1 will refer to the memory address variable1, but not the value.
In case you want to put a new value into a variable using a pointer then you add a * character in front of the pointer name such as *pointer1 shown below.
*pointer1 = 100;
Now the variable named variable1 has a value of 100.
The following code example explains this better.
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 variable1 to pointer1 in the third line. Now both variable1 and pointer1 points to same memory location. After that, we printed the value of variable1 which equals 50. We then assign a value of 100 to the memory address of variable1 using pointer1. 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.
Character Pointers
As discussed earlier, a pointer can hold any data type. Same is the case with characters and strings. Pointers can refer to memory addresses of any string or character. In fact pointers gives you more control over your strings by using array indexes to reference each character of a string. The following example explains this concept. You must use const before char in Visual C++ for this example to work without errors.
Example 2:
const char * pointer1;
pointer1 = "TBYtutorials";
cout << pointer1 << endl;
cout << pointer1[0] << endl;
cout << pointer1[1] << endl;
pointer1++;
cout << pointer1 << endl;
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 an ordinary character string and a pointer to character string. An ordinary character string is constant and cannot be incremented like a pointer. A pointer simply points to the first memory location of the character string and prints the whole string if outputted. In this case we incremented a pointer with ++, so the pointer now points to the next index. Now the output string starts from the second character as “BYtutorials” 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. The 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 3:
int abc [4] = {10, 41, 32, 15};
int *pointerarray [4];
for (int i = 0; i < 4; i++)
{
pointerarray[i] = &abc[i]; // store abc memory addresses 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 4:
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 abc memory addresses 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 assigned 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";
}
In this code, we have initialized the pointer with the memory address of the array. Initially the 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 bytes, 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. The following is the output of the above code. Note that your output of memory addresses will be different as this depends on where your program is located in memory.
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 const char *ptr;
In the case of char abc[] it holds the actual data of the string in the form of individual characters in contiguous array index. On the other hand const char *ptr points to the starting address of the array and we can continuously move to the next memory address using pointer arithmetic. The following project explains this concept. In this example the 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()
{
const char *ptr = "Welcome to TBY tutorials"; //put pointer at start of string
for (int i = 0; i < 24; i++)
{
cout << ptr << endl;
ptr++;
}
}
Output:
You might also want to read:
Part 1 – Installing Visual Studio C++
Part 3 – Conditional “if” Statement
Part 4 – else if Statement in C++
Part 7 – Pointers
If you like this page please share with your friends.