Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Understanding Basics of Pointers in C++ (http://www.go4expert.com/articles/understanding-basics-pointers-cpp-t29962/)

usmanmalik 10Jan2014 17:00

Understanding Basics of Pointers in C++
 
Pointers are often considered the most confusing concept of C++ language despite of being extremely straight forward. Developers who are newbie to C++ programming get perplexed while understanding pointers. However, by paying attention to the concept theory and practical examples, pointers can be understood quite easily. In this tutorial, we are going to give you a detailed and at the same time easy to grasp overview of pointers.

What are Pointers?



Pointers is an advanced and at the same time core feature of C and C++ programming. Everything in a computer is stored in memory. Variables you define in your program are stored at physical locations in the memory. In order to access the content of the variable you use variable name. Similarly, pointers are the variables that store memory address of the content. Using pointer variables you can access physical locations of the content of code in memory. Though, C and C++ extensively use pointers to perform certain functions, however there are many advanced languages such as Java and Visual basic that do not use pointers. In Java, a variation of pointers called references are used that perform almost similar function to that of pointer

You must be considering why use pointers; what the benefits of accessing and manipulating memory address of a variable are? The next section answers your questions.

Uses of pointers



In C and C++ pointers are used to perform variety of functions. Some of those have been listed below.
  • Pointers are used to pass arguments to the function when the function has to modify the original data or if we want our function to act upon multiple values.
  • Pointers are also helpful in passing arrays and strings to the function as arguments.
  • Pointers can be used to access elements of an array.
  • If you want to get memory address of certain variable from the system you can use pointers.
  • The last and most important use of pointers is that they can be used to create several data structures for example linked-lists.
  • Pointers are extremely helpful for low level programming purposes such as garbage collection etc.

Accessing Memory address



Accessing memory address of a variable is extremely simple task. You just have to append ampersand “&” sign before the name of the variable. This concept will be demonstrated with the help of a simple example. Here we will declare three variables of type integer and display their values. Then we will use ampersand sign before the variable name and print it. You will see that the memory address of the variables will be printed.

Note: All examples in this tutorial have been written in Visual C++ with VS 2010 as the IDE.

Example1
Code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
        int a,b,c;
        a= 10;
        b=20;
        c=30;

        cout<<"The values of a, b and c are "<<a<<", "<<b<<" and "<<c<<" respectively."<<endl;
        cout<<"The address of a, b and c are "<<&a<<", "<<&b<<" and "<<&c<<" respectively."<<endl;

}

Output1

http://imgs.g4estatic.com/articles/p...pp/output1.png

Carefully look at the output. In line 1 the actually values of variables a, b and c are displayed where as in line 2 the memory addresses of these variables are displayed. Note, there are 8 characters for each memory address; this is due to the reason that in C++, memory address are interpreted in hexadecimal arithmetic by the insertion operator.

Pointer Variables



In Example1 we simply access the memory address of the variable and displayed them on the screen. However, pointer is a far vaster and technically advanced concept. You might wonder how to use the memory address once it has been accessed. Here the concept of pointer variable comes to play. You can store integers in int type variables, characters in char type and strings in string type. The variable which stores the memory address is called a pointer variable. Example2 further explains, how to declare a pointer variable and how to access the contents stored in the memory address. Have a look at it.

Example2
Code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
        int a,b,c;
        a= 10;
        b=20;
        c=30;

        int* pointera, * pointerb, * pointerc;

        pointera = &a;
        pointerb= &b;
        pointerc= &c;

        cout<<pointera<<endl;  // Will display the memory address of a
        cout<<pointerb<<endl;  // Will display the memory address of b
        cout<<pointerc<<endl<<endl;  // Will display the memory address of c

        cout<<*pointera<<endl;  // Will display the value of a
        cout<<*pointerb<<endl;  // Will display the value of b
        cout<<*pointerc<<endl;  // Will display the value of c

        *pointera = 100;      // Changing value of memory address of variable a
        *pointerb = 200;      // Changing value of memory address of variable b
        *pointerc = 300;      // Changing value of memory address of variable c

        cout <<endl<<a<<endl<<b<<endl<<c;  // Displaying Changed Values through variables

}

Pay attention to the code in Example2. We are going to explain many important concepts based upon this code. First of all we have declared three variables a, b and c of type integer and have initialized them with 10, 20 and 30 as we did in the previous example.

In the next line we declare three variables of pointer type. See how we defined these pointers.

Code:

int* pointera, * pointerb, * pointerc;
Defining a pointer variable is a three step process. Firstly you have to specify type of variable whose memory address will be stored in the pointer variable. For example if you want to store the memory address of the integer, you will specify int as the pointer type. Next you append ‘*’ followed by the name of the pointer variable. Note that the process of defining pointer variable to integer memory address is similar to defining a simple integer variable, except ‘*’ is added between the variable type and variable name. Therefore we define the pointer variable named pointera that can hold memory address of an integer as int * pointera;

You can also declare multiple variable in a single line of code by separating pointer variable with the comma; however, you will have to place a ‘*’ before each variable name.

Coming back to Example2, we have then assigned the memory address of variables a, b and c to pointer variables pointera, pointerb and pointerc respectively and displayed these pointers. Since, pointer variables hold the memory address; the hexadecimal memory addresses will be displayed.

Now, how about accessing the value of the variable, instead of memory address? Using pointer variables, we can not only access the memory address of the variable but also the value stored in that variable. We can do this by simply prefixing * with the name of the pointer variable.

For example if pointera holds the memory address of integer variable ‘a’ and we want to access the value stored in the variable ‘a’ using the pointera by prefixing * with it as *pointera. In Example2, we have retrieved and displayed the value of variables a, b and c this way.

Then we have changed the values stored in the memory address of the pointera, pointerb and pointer. Since, variables a, b and c share the same memory address, therefore after assigning values 100, 200 and 300 to pointers variables of a, b and c. The variables a, b and c are displayed. They will contain the new variables. The output of the Example2 is as follows.

Output2

http://imgs.g4estatic.com/articles/p...pp/output2.png

Calling Function by Reference Using pointers



In one of our earlier tutorials, we explained that we can pass arguments to a function in two ways. We can either pass arguments by value to the function or by reference. Pointers can be used to pass arguments by reference to the function. This way calling function can modify the original values. Secondly, a function cannot return more than one value but by passing multiple arguments by reference we can achieve the same functionality. In our next example, we will explain how we can use pointer variables to pass arguments by reference to a function.

Example3
Code:

#include <iostream>
#include <string>
using namespace std;

void square(int* a, int* b) // Receiving address in pointers a and b
{
        *a = *a * *a; // Multiplying the values of pointer a
        *b = *b * *b; // Multiplying the value of pointer b
}

int main()
{
        int num1, num2;
        cout <<"Enter the first number:";
        cin>>num1;
        cout <<"Enter the second number:";
        cin>>num2;

        square (&num1, &num2); // Passing the memory address of numbers
        cout << "The sum of squares of two numbers you entered is:"<<num1+num2;

}

In Example3, we want that user enters two numbers and we can print the sum of squares of the two numbers entered by the user. If we pass the two numbers entered by the users as arguments to the square function by value, the function can calculate the square of both of these numbers. But problem here is that square function could only return one squared value. But we want the square of two values.

In order to obtain square of two values from the function, we passed the memory address of the two numbers to the function. Look at the square function. The memory address of the number passed will be stored in pointers ‘a’ and ‘b’ respectively. Inside the body, we have multiplied the value with itself and stored the answer in the same pointer. We did this with both of the passed pointers. Now since we have changes the values stored in the memory address using pointers, the original values of num1 and num1 would also change and contain square of both the numbers. This way we have achieved similar functionality of returning multiple values from a single function. The output is shown as follows

Output3

http://imgs.g4estatic.com/articles/p...pp/output3.png

Memory Management Using ‘new’ and ‘delete’



We know that we have to define the size of an array using some constant. In order to store the name of a person in array we usually declare an array of size 100 because we are expecting the name to be shorter than 100 words. This approach has two disadvantages: if the name is greater than 100 characters, we cannot store the name and stack will overflow, secondly if name is smaller than 100 characters we are wasting the remaining memory. We need to somehow dynamically allocate the memory for the array so that we can store as much data as we want and additional memory is not wasted. Using pointers, we can do this. In Example4, this concept has been explained.

Example4
Code:

#include <iostream>
#include <string>
using namespace std;

int main()
{

        char * statement = "go4Expert have the best tutorials";
        int length = strlen(statement);
        char * pointer = new char[length+1];
        strcpy(pointer, statement);
        cout <<"Pointer = "<<pointer<<endl;
        delete[] pointer;

}

In Example4, we have defined a character type pointer named statement and stored a string in the pointer. Secondly, we have found the length of the string using strlen built-in function.
Next line is very important

Code:

char * pointer = new char[length+1];
This line does the actual business. The line tells the compiler that a space in memory should be created which can hold character string of length ‘length + 1’, one additional space for ‘\0’. Here we are dynamically allocating the memory space of our desired length. Then we copied the string in the ‘statement’ pointer to ‘pointer’ and displayed it on the output screen. Note here that after using the dynamically created pointer, we have deleted it using the delete[] keyword here. Delete keyword followed by opening and closing brackets will vacate the memory occupied by the actual pointer.

A pointer is an extremely vast concept that cannot be covered in a single tutorial. We can do lot of things using pointers, we can single and multi –dimensional arrays using pointers, you can do arithmetic with pointers and can perform virtually everything. In order to further understand pointers and its functionality, you should try to implement the examples given in this tutorial. Try to write your own code and in case if you don’t understand anything, feel free to comment. Also, keep visiting this site for more interesting and useful tutorials.

shine 11Jan2014 15:29

Re: Understanding Basics of Pointers in C++
 
Hi Mailk,

Thanks for the article . Will you tell me how we can redefine the new operator in C++. Any idea please post a replay..

Thanks
Shine joseph


All times are GMT +5.5. The time now is 22:54.