Cpp Programming Pointers And Pointer Arithmetic Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    10 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of CPP Programming Pointers and Pointer Arithmetic

Explanation and Important Information on CPP Programming: Pointers and Pointer Arithmetic

Introduction to Pointers:

Example of Declaring and Using a Pointer:

int x = 10;       // Integer variable
int* ptr = &x;    // Pointer to integer, initialized with the address of x

std::cout << "Value of x: " << x << std::endl;           // Outputs 10
std::cout << "Address of x: " << ptr << std::endl;     // Outputs memory address of x
std::cout << "Value through pointer: " << *ptr << std::endl;  // Dereferences ptr to get x's value (10)

Pointer Arithmetic:

Pointer arithmetic involves using arithmetic operations on pointers to navigate through memory. In C++, you can add or subtract integers from pointers, and you can also subtract one pointer from another. These operations are heavily used in arrays and dynamic memory management.

Basic Operations:

  • Increment and Decrement Operators: These modify the memory address stored in a pointer by adding or subtracting the size of its data type.
  • Addition and Subtraction with Integers: These operations move the pointer forward or backward by the number of bytes equal to the size of the pointer's data type multiplied by the integer.

Example of Pointer Arithmetic:

int arr[5] = {10, 20, 30, 40, 50};
int* ptr = arr;     // Pointer initialized with the address of the first element

std::cout << "Value at ptr: " << *ptr << std::endl;     // 10
std::cout << "Value at ptr+1: " << *(ptr+1) << std::endl; // 20
std::cout << "Value at ptr+2: " << *(ptr+2) << std::endl; // 30

Pointer and Array Relationship:

Arrays in C++ are intrinsically related to pointers. The name of an array often acts like a constant pointer to its first element. This means that pointer operations can be performed on arrays using pointer arithmetic.

Example:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement CPP Programming Pointers and Pointer Arithmetic

Introduction to Pointers in C++

A pointer in C++ is a variable that stores the memory address of another variable as its value. Pointers have many uses, including the manipulation of arrays and implementation of data structures like linked lists.

Declaring and Initializing Pointers

To declare a pointer, you need to specify the type of the variable that the pointer will point to, followed by an asterisk (*) and the name of the pointer.

Example:

#include <iostream>

int main() {
    int var = 3;          // Variable of type int
    int *ptr;             // Pointer to int

    ptr = &var;           // Store the address of var in ptr

    std::cout << "Value of var: " << var << std::endl;
    std::cout << "Address of var: " << &var << std::endl;
    std::cout << "Address stored in ptr: " << ptr << std::endl;
    std::cout << "Value pointed to by ptr: " << *ptr << std::endl;

    return 0;
}

Output:

Value of var: 3
Address of var: 0x7ffee6b7d9ac      // This will be different on your machine
Address stored in ptr: 0x7ffee6b7d9ac // This will be the same as the address of var
Value pointed to by ptr: 3

Here, int *ptr declares a pointer named ptr that can point to an integer. ptr = &var stores the address of var in ptr. *ptr is used to dereference the pointer and access the value stored at the address it points to.

Pointer Arithmetic

Pointer arithmetic involves using arithmetic operators like +, -, ++, --, and += on pointers. However, these operations are only allowed on pointers to arrays.

Important Notes:

  • Adding 1 to a pointer increments it by the size of the type it points to, not just 1 byte.
  • Subtracting 1 from a pointer decrements it by the size of the type it points to.

Example:

#include <iostream>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr = arr;         // Point to the first element of arr

    std::cout << "ptr points to value: " << *ptr << std::endl;

    ptr = ptr + 1;          // Move to the next element
    std::cout << "ptr points to value: " << *ptr << std::endl;

    ptr += 2;               // Move to the third after next element
    std::cout << "ptr points to value: " << *ptr << std::endl;

    ptr = ptr - 1;          // Move back to the previous element
    std::cout << "ptr points to value: " << *ptr << std::endl;

    ptr--;                  // Decrement to the previous element
    std::cout << "ptr points to value: " << *ptr << std::endl;

    return 0;
}

Output:

ptr points to value: 10
ptr points to value: 20
ptr points to value: 50
ptr points to value: 40
ptr points to value: 30

In this example, ptr is initially pointing to the first element of the array arr. We use ptr + 1, ptr += 2, ptr - 1, and ptr-- to navigate through the array and access different elements by adjusting the pointer.

Pointer Addition

Adding an integer to a pointer moves the pointer forward by that many elements in the array.

Example:

#include <iostream>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr = arr;

    std::cout << "First element: " << *ptr << std::endl;     // Access first element
    std::cout << "Second element: " << *(ptr + 1) << std::endl; // Access second element
    std::cout << "Third element: " << *(ptr + 2) << std::endl;   // Access third element

    return 0;
}

Output:

First element: 10
Second element: 20
Third element: 30

Pointer Difference

Subtracting one pointer from another gives the number of elements between them in the array.

Example:

#include <iostream>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr1 = arr;
    int *ptr2 = arr + 3;

    int diff = ptr2 - ptr1; // Difference in array indices

    std::cout << "Difference: " << diff << std::endl; // Output: 3

    return 0;
}

Output:

Difference: 3

NULL Pointers

A NULL pointer is a pointer that does not point to any particular memory location and has a value of 0.

Example:

#include <iostream>

int main() {
    int *ptr = NULL;
    int var = 5;

    std::cout << "Value of ptr before assignment: " << ptr << std::endl;

    ptr = &var;
    std::cout << "Value of ptr after assignment: " << ptr << std::endl;

    if (ptr != NULL) {
        std::cout << "ptr points to value: " << *ptr << std::endl;
    } else {
        std::cout << "ptr is NULL" << std::endl;
    }

    return 0;
}

Output:

Value of ptr before assignment: 0x0
Value of ptr after assignment: 0x7ffee6b7d9ac
ptr points to value: 5

Pointers to Arrays

Pointers can also be used to point to entire arrays. However, the pointer will point to the first element of the array.

Example:

#include <iostream>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr = arr;   // Points to the first element of arr

    std::cout << "Address of first element: " << &arr[0] << std::endl;
    std::cout << "Address stored in ptr: " << ptr << std::endl;

    for (int i = 0; i < 5; i++) {
        std::cout << "Element at index " << i << ": " << *(ptr + i) << std::endl;
    }

    return 0;
}

Output:

Address of first element: 0x7ffee6b7d9ac
Address stored in ptr: 0x7ffee6b7d9ac
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Pointers in Functions

Pointers can be used to pass arguments to functions by reference, allowing the function to modify the original variables.

Example:

#include <iostream>

// Function to swap two values using pointers
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 5, y = 10;

    std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;

    swap(&x, &y);

    std::cout << "After swap: x = " << x << ", y = " << y << std::endl;

    return 0;
}

Output:

Before swap: x = 5, y = 10
After swap: x = 10, y = 5

In the swap function, the addresses of x and y are passed. The values pointed to by these addresses are then swapped.

Conclusion

Pointers are a powerful feature in C++ that allow you to manipulate memory addresses directly. This includes working with dynamic memory allocation, implementing complex data structures, and optimizing performance. However, they require careful handling to avoid common pitfalls like dereferencing NULL pointers or causing memory leaks.

Top 10 Interview Questions & Answers on CPP Programming Pointers and Pointer Arithmetic

1. What is a pointer in C++ and how do you declare one?

Answer: A pointer is a variable that holds the memory address of another variable. In C++, pointers are declared by using an asterisk (*) before the variable name. For example, int* ptr; declares a pointer variable named ptr that can store the address of an integer.

2. How do you initialize a pointer with the address of a variable?

Answer: You initialize a pointer with the address of a variable using the address-of operator (&). For example:

int num = 10;
int* ptr = &num;

In this code, ptr is initialized with the address of num.

3. What is the difference between int* ptr and int *ptr?

Answer: There is no difference between int* ptr and int *ptr. Both declarations declare a pointer to an integer. The space between the int and * is optional.

4. How do you access the value stored at the memory address pointed to by a pointer?

Answer: You access the value stored at the memory address pointed to by a pointer using the dereference operator (*). For example:

int num = 10;
int* ptr = &num;
std::cout << *ptr;  // Outputs 10

Here, *ptr gives the value stored at the address stored in ptr, which is the value of num.

5. What is pointer arithmetic in C++?

Answer: Pointer arithmetic involves performing arithmetic operations (addition, subtraction, increment, decrement) on pointers. For example, incrementing a pointer increases its memory address by a size equal to the type of data it points to. Here’s an example:

int arr[4] = {10, 20, 30, 40};
int* ptr = arr;
ptr++;  // ptr now points to the second element of the array (20)

6. Can you perform arithmetic with pointers to void in C++?

Answer: No, you cannot perform arithmetic with pointers to void in C++ because the size of the data type is unknown. For arithmetic operations, you must use pointers to explicitly defined types (like int*, char*, etc.).

7. What is the null pointer in C++ and how do you assign it?

Answer: The null pointer is a pointer that does not point to any valid location in memory. It can be assigned using the nullptr keyword or the literal 0 (in C++98 and before). It is a good practice to assign a pointer to nullptr if it does not point to any valid memory location. For example:

int* ptr = nullptr;

8. What is a wild pointer in C++?

Answer: A wild pointer is a pointer that points to a memory address that has not been explicitly assigned. Once a pointer is declared but not initialized, it can become a wild pointer, pointing to an undefined memory location. To prevent errors, always initialize pointers to nullptr or a valid memory address.

9. Can you assign the address of a variable to a pointer of a different type in C++?

Answer: While you can assign the address of a variable to a pointer of a different type without any compiler error, it can lead to undefined behavior and is generally not recommended unless you are absolutely sure of the types involved and align the memory correctly. For example:

int num = 10;
double* ptr = reinterpret_cast<double*>(&num);  // Not recommended and likely undefined

10. What is the difference between delete and delete[] in C++?

Answer: delete is used to deallocate memory allocated for a single element, whereas delete[] is used to deallocate memory allocated for an array of elements. Using the correct corresponding operator is crucial to properly release memory and avoid memory leaks.

You May Like This Related .NET Topic

Login to post a comment.