Curriculum
Course: Learn C++
Login

Curriculum

Learn C++

Text lesson

Introduction to Pointers in C++

In this lesson, you will learn

  • Understanding Pointers
  • Declaring and Initializing Pointers
  • Dereference Operator
  • Function Calls(Call by Value or Call by Pointers)

 

1. Understanding Pointers

Before understanding the pointers. Let us understand the following memory map to store an integer variable x with a value of 5.

PointerNotation

Here, you can see the computer has selected a random memory location 0x61ff0c to store an integer variable x. The location number 0x61ff0c is not a number to be relied upon, because some other time the computer may choose a different location for storing the value 5.

The important point is, the x’s address in memory is a number. It is known as the address of a variable x.

So, the following question arises.

How and where to store this address(0x61ff0c) of a variable i.e. x?

Answer: Pointers.

The ordinary variable can’t hold this address. It can be held by a pointer only.

 

Let’s explore the concept of Pointers in C++.

What is Pointers

  • A pointer is a variable that stores the memory address of another variable.
  • Instead of holding a data value directly, a pointer holds the location where the value is stored
  • Pointers are powerful tools in C++ for dynamic memory allocation, array manipulation, and efficient function argument passing.

 

Basics of Pointers?

1. Declaration: To declare a pointer, you use the asterisk (*) symbol. For example, to declare a pointer to an integer:

int* ptr;


2. Initialization: Pointers are initialized by assigning them the address of another variable. The address-of operator (&) is used to get the address of a variable. For example:

int var = 5;
int* ptr = &var;


3. Dereferencing: To access the value stored at the address a pointer is pointing to, you use the dereference operator (*). For example:

int value = *ptr; // value now holds 5


 

A variable that holds an address value is called a pointer variable, or simply a pointer.

int *ptr; // value now holds 5

 

The asterisk means pointer to. Thus the statement defines the variable ptr as a pointer to int. This is another way of saying that this variable can hold the addresses of integer variables.

The syntax used in C++ allows pointers to any type to be declared:

char* cptr; // pointer to char
int* iptr; // pointer to int
float* fptr; // pointer to float
Distance* distptr; // pointer to user-defined Distance class
and so on.

 

Displaying the Address of a Variable

To display the address of a variable, you can use the & operator along with the pointer.

Here is an example demonstrating the declaration, initialization, and use of pointers to display the address of a variable:

    Example -1: Printing The Addresses of Variables

    #include 
    using namespace std;
    
    int main() {
        int var = 5;  // Declare an integer variable
        int* ptr = &var;  // Declare a pointer and initialize it with the address of var
    
        // Display the value of the variable
        cout << "Value of var: " << var << endl;
    
        // Display the address of the variable
        cout << "Address of var: " << &var << endl;
    
        // Display the address stored in the pointer (should be the same as the address of var)
        cout << "Address stored in ptr: " << ptr << endl;
    
        // Display the value pointed to by the pointer
        cout << "Value pointed to by ptr: " << *ptr << endl;
    
        return 0;
    }
    
    

     

    Output

    Value of var: 5
    Address of var: 0x61ff08
    Address stored in ptr: 0x61ff08
    Value pointed to by ptr: 5
    

     

    Example -2: Printing The Addresses of Variables

    // addresses of variables
    #include 
    using namespace std;
    int main()
    {
        int var1 = 11; //define and initialize
        int var2 = 22; //three variables
        int var3 = 33;
        cout << "Address of var1 "<< &var1 << endl //print the addresses
        << "Address of var2 "<< &var2 << endl //of these variables
        << "Address of var3 "<< &var3 << endl;
        return 0;
    }
    
    

    Output

    Address of var1 0x61ff0c
    Address of var2 0x61ff08
    Address of var3 0x61ff04
    
    
    

    Explanation

    The addresses appear in descending order because local variables are stored on the stack, which grows downward in memory.

    If we had used global variables, they would have ascending addresses, since global variables are stored on the heap, which grows upward.

    Again, you don’t need to worry too much about these considerations, since the compiler keeps track of the details for you.

     

    Example-2: Printing The Address of a Pointer Variables

    //PointersEx2.cpp
    // pointers (address variables)
    #include <iostream>
    using namespace std;
    int main()
    {
        int var1 = 11; //two integer variables
        int var2 = 22;
        cout << &var1 << endl //print addresses of variables
        << &var2 << endl << endl;
    
        int* ptr; //pointer to integers
    
        ptr = &var1; //pointer points to var1
        cout << ptr << endl; //print pointer value
    
        ptr = &var2; //pointer points to var2
        cout << ptr << endl<< endl; //print pointer value
        
        cout << &ptr << endl; //print addresses of pointer variables
        return 0;
    }
    

     

    Output

    0x61ff0c
    0x61ff08
    
    0x61ff0c
    0x61ff08
    
    0x61ff04
    

     

    Note: A pointer can hold the address of any variable of the correct type

     

    You can use a pointer to assign a value to a variable, and then assign that value to another variable.

    Example

    // PointersEx4.cpp
    // other access using pointers
    #include <iostream>
    using namespace std;
    int main()
    {
        int var1, var2; //two integer variables
        int* ptr; //pointer to integers
        ptr = &var1; //set pointer to address of var1
        *ptr = 37; //same as var1=37
        var2 = *ptr; //same as var2=var1
        cout << "var2:"<<var2 << endl; //verify var2 is 37
        return 0;
    }
    

    Output

    var2=37
    
    
    

     

    2. Understanding Function Calls

    In C++, functions can be called in two primary ways: call by value and call by pointer. These methods define how arguments are passed to functions, affecting how the function interacts with the arguments.

    CallByValueAndPointers

    1. Call by Value

    When a function is called by value, a copy of the argument’s value is passed to the function. Changes made to the parameter inside the function do not affect the original argument.

    Example of Call by Value

    #include<iostream>
    using namespace std;
    
    void modifyValue(int num) {
        num = 10; // Modify the local copy
        cout << "Inside modifyValue, num: " << num << endl;
    }
    
    int main() {
        int a = 5;
        cout << "Before modifyValue, a: " << a << endl;
        modifyValue(a); // Pass by value
        cout << "After modifyValue, a: " << a << endl;
        return 0;
    }
    
    
    
    

    Output:

    Before modifyValue, a: 5
    Inside modifyValue, num: 10
    After modifyValue, a: 5
    
    

    The value of a before and after the function call remains 5, demonstrating that the original value is not modified.

     

    2. Call by Pointer

    When a function is called by pointer, the address of the argument is passed to the function. This allows the function to modify the original variable’s value.

    Example of Call by Pointer

    #include<iostream>
    using namespace std;
    
    void modifyValue(int* numPtr) {
        *numPtr = 10; // Modify the value at the address pointed to
        cout << "Inside modifyValue, *numPtr: " << *numPtr << endl;
    }
    
    int main() {
        int a = 5;
        cout << "Before modifyValue, a: " << a << endl;
        modifyValue(&a); // Pass by pointer
        cout << "After modifyValue, a: " << a << endl;
        return 0;
    }
    
    
    
    

    Output:

    Before modifyValue, a: 5
    Inside modifyValue, *numPtr: 10
    After modifyValue, a: 10
    
    
    

    The value of a before the function call is 5, and after the function call, it becomes 10, demonstrating that the original value is modified.

     

    Real-Life Analogy

    • Call by Value: Imagine you are given a photocopy of a document. Any changes you make to the photocopy do not affect the original document.
    • Call by Pointer: Imagine you are given the original document. Any changes you make to the document directly affect the original.

     

     

    Exercises: Using Functions

    1. Write a function to find the binary equivalent of a given decimal integer and display it.
    2. A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number.

     

    Exercises: Using Pointers

    Exercise 1: Swapping Two Variables

    Description: Write a function that swaps the values of two variables using pointers.

    Problem Statement: Implement a function swapValues that takes two integer pointers and swaps their values.

     

    Exercise 2: Incrementing a Value

    Description: Write a function that increments the value of an integer using a pointer.

    Problem Statement: Implement a function incrementValue that takes an integer pointer and increments the value it points to by 1.

     

     


    End of the lesson….enjoy learning

     

     

    Student Ratings and Reviews

     

    5.0
    5.0 out of 5 stars (based on 1 review)
    Excellent100%
    Very good0%
    Average0%
    Poor0%
    Terrible0%

     

     

    August 28, 2024

    crazy

     

     

    Submit a Review