Topic 12: Pointers

Pointers are a powerful feature in C++ that allow you to manipulate memory directly. A pointer is a variable that holds the memory address of another variable.

Declaring and Initializing Pointers

To declare a pointer, specify the type of the variable it points to, followed by an asterisk (*) and the pointer name. You can initialize a pointer by assigning it the address of a variable using the address-of operator (&):

Example: Declaring and Initializing a Pointer
  • 
    #include 
    using namespace std;
    
    int main() {
        int var = 10;
        int *ptr = &var;
    
        cout << "Value of var: " << var << endl;
        cout << "Address of var: " << &var << endl;
        cout << "Value of ptr (address of var): " << ptr << endl;
        cout << "Value at the address stored in ptr: " << *ptr << endl;
    
        return 0;
    }
                                        

Pointer Operators

Pointers use two main operators:

  • Address-of operator (&): Returns the memory address of a variable.
  • Dereference operator (*): Returns the value stored at the memory address pointed to by the pointer.

Null Pointers

A pointer that is not assigned any memory address is called a null pointer. A null pointer points to nothing and can be created by assigning the constant NULL or nullptr to the pointer:

Example: Null Pointer
  • 
    #include 
    using namespace std;
    
    int main() {
        int *ptr = nullptr;
    
        if (ptr == nullptr) {
            cout << "Pointer is null" << endl;
        }
    
        return 0;
    }
                                        

Pointers and Arrays

Pointers can be used to access elements of an array. The name of an array acts as a pointer to its first element. You can use pointer arithmetic to traverse the array:

Example: Pointers and Arrays
  • 
    #include 
    using namespace std;
    
    int main() {
        int arr[5] = {1, 2, 3, 4, 5};
        int *ptr = arr;
    
        for (int i = 0; i < 5; ++i) {
            cout << "Element " << i << ": " << *(ptr + i) << endl;
        }
    
        return 0;
    }
                                        

Pointers to Pointers

C++ allows you to create pointers to pointers, which means a pointer that stores the address of another pointer:

Example: Pointers to Pointers
  • 
    #include 
    using namespace std;
    
    int main() {
        int var = 10;
        int *ptr = &var;
        int **ptr2 = &ptr;
    
        cout << "Value of var: " << var << endl;
        cout << "Address of var: " << &var << endl;
        cout << "Value of ptr: " << ptr << endl;
        cout << "Address of ptr: " << &ptr << endl;
        cout << "Value of ptr2: " << ptr2 << endl;
        cout << "Value at the address stored in ptr2: " << *ptr2 << endl;
        cout << "Value at the address stored in the pointer pointed to by ptr2: " << **ptr2 << endl;
    
        return 0;
    }
                                        

Function Pointers

Pointers can also be used to point to functions. Function pointers can be useful for implementing callback functions or for passing functions as arguments to other functions:

Example: Function Pointers
  • 
    #include 
    using namespace std;
    
    void displayMessage() {
        cout << "Hello, World!" << endl;
    }
    
    int main() {
        void (*funcPtr)() = displayMessage;
        funcPtr();
    
        return 0;
    }
                                        

Practice Questions

  1. What is the difference between the & (address-of) and * (dereference) operators in C++?
  2. What is a NULL pointer?
  3. What are wild pointers, and why are they dangerous?
  4. What is pointer arithmetic in C++?
  5. What is a void pointer? How is it different from other pointers?
  6. How do you dynamically allocate memory for a single variable using pointers in C++, illustrate with an example?
  7. What is the difference between new and delete in C++?
  8. What are dangling pointers, and how can they be avoided?
  9. What is the difference between passing by value and passing by pointer to a function in C++?
  10. What is a pointer to a pointer? How do you declare and use it?
  11. What is a constant pointer?
  12. What is the difference between a constant pointer and a pointer to a constant?
  13. What are the advantages and disadvantages of using pointers in C++?
  1. Pointer Dereferencing: Write a C++ program to swap two numbers using pointers.
    • Declare two integer variables and assign them values.
    • Write a function that takes two pointers as arguments and swaps the values of the variables they point to.
    • Use the function to swap the values of two variables.
  2. Array and Pointers: Write a C++ program to input and display the elements of an array using pointers.
    • Declare an array of integers.
    • Use a pointer to input elements into the array.
    • se the same pointer to display the elements of the array.
  3. Pointer to Function: Write a C++ program that uses a pointer to a function. Define a function that adds two integers and then use a pointer to call this function.
    • Write a function that takes two integers as arguments and returns their sum.
    • Declare a pointer to the function.
    • Use the pointer to call the function and display the result.
  4. Pointer to an Array: Write a C++ program to reverse an array using pointers.
    • Declare an array of integers.
    • Use a pointer to iterate over the array.
    • Use the pointer to reverse the elements in the array in place (without using an additional array).
  5. Dynamic Memory Allocation: Write a C++ program to dynamically allocate memory for an integer, assign it a value, and then free the allocated memory.
    • Use the new operator to dynamically allocate memory for an integer.
    • Assign a value to the dynamically allocated integer.
    • Display the value and then free the memory using the delete operator.
  6. Pointer Arithmetic: Write a C++ program to demonstrate pointer arithmetic. Declare an array of integers and use a pointer to print each element of the array by incrementing the pointer.
    • Declare an array of integers.
    • Use a pointer to point to the first element of the array.
    • Increment the pointer to print all elements of the array.
  7. Pointer to Pointer: Write a C++ program to demonstrate the use of a pointer to a pointer. Declare an integer variable, use a pointer to point to it, and then use a pointer to the pointer to access the value of the variable.
    • Declare an integer variable and assign a value to it.
    • Declare a pointer to point to the integer.
    • Declare a pointer to the pointer and use it to display the value of the integer.
  8. Pointers and Strings: Write a C++ program to input a string and print it using a pointer.
    • Declare a character array to store a string.
    • se a pointer to input the string.
    • Use the pointer to display the string.
  9. Dynamic Array Using Pointers: Write a C++ program to dynamically allocate memory for an array of integers, input the elements, and then calculate their sum.
    • Use the new operator to dynamically allocate memory for an array of integers.
    • Input the elements of the array using a pointer.
    • Calculate and display the sum of the array elements.
    • Free the dynamically allocated memory using delete[].
  10. Null Pointer Check: Write a C++ program that checks if a pointer is a NULL pointer before dereferencing it.
    • Declare an integer pointer and initialize it to nullptr.
    • Use an if condition to check if the pointer is nullptr before dereferencing it.
    • If the pointer is not nullptr, dereference it to print its value; otherwise, display an error message.
  11. Modify Variable through Pointer: Write a C++ program to modify the value of a variable through a pointer.
    • Declare an integer variable and assign it a value.
    • Declare a pointer to store the address of the variable.
    • Use the pointer to modify the value of the variable and print the modified value.
  12. Pass by Pointer: Write a C++ program where you pass a pointer to a function. The function should modify the value of the variable using the pointer.
    • Declare an integer variable and assign a value to it.
    • Write a function that takes a pointer as an argument and modifies the value of the variable.
    • Call the function and display the modified value.
  13. Memory Leak Demonstration: Write a C++ program to demonstrate a memory leak and show how to fix it.
    • Dynamically allocate memory for an integer using new but forget to free the memory (this creates a memory leak).
    • Modify the program to correctly free the allocated memory using delete.
  14. Pointer to Constant: Write a C++ program to demonstrate the concept of a pointer to a constant.
    • Declare a constant integer.
    • Declare a pointer to a constant and use it to access the value.
    • Attempt to modify the value through the pointer (which should give a compile-time error).
Coming Soon...