C++ Pointers

GitHub Code
1. What Are Pointers?

A pointer in C++ is a variable that stores the memory address of another variable. Pointers are powerful tools because they allow you to manipulate data in memory directly, making them useful for dynamic memory allocation, passing large objects efficiently, and creating complex data structures like linked lists, trees, etc.

2. Basic Pointer Syntax

  • Declaring a pointer:
    int* ptr;
  • Here, ptr is a pointer to an integer.
  • Getting the address of a variable (using the address-of operator &):
    int x = 5;
    ptr = &x; // ptr now holds the memory address of x
  • Accessing the value pointed to by a pointer (using the dereference operator *):
    int value = *ptr; // value is now 5 (the value stored in x)

3. Pointer Example Program

Let’s create a simple program that demonstrates the use of pointers in C++.

Program: PointerBasics.cpp

code#include <iostream>

int main() {
// Declare an integer variable
int num = 10;

// Declare a pointer variable that will store the address of num
int* ptr = &num;

// Output the address stored in the pointer
std::cout << "The address of num is: " << ptr << std::endl;

// Output the value of num using the pointer
std::cout << "The value of num using pointer dereferencing: " << *ptr << std::endl;

// Modify the value of num using the pointer
*ptr = 20;

// Output the new value of num after modification through the pointer
std::cout << "The new value of num is: " << num << std::endl;

return 0;
}

Explanation of the Program:

  • int num = 10;
    We declare a normal integer variable num and assign it the value 10.
  • int* ptr = &num;
    We declare a pointer ptr of type int* and assign it the address of num (using the & operator).
  • std::cout << ptr << std::endl;
    This outputs the memory address where num is stored, which is now held by ptr.
  • std::cout << *ptr << std::endl;
    This outputs the value of num, but accessed via the pointer ptr (using the * operator to dereference the pointer).
  • *ptr = 20;
    We modify the value of num by dereferencing the pointer and assigning a new value to it.

4. Pointer and Arrays

Pointers can also be used to work with arrays since arrays are stored in contiguous memory blocks.

Example: Pointers with Arrays

#include <iostream>

int main() {
// Declare an array of integers
int arr[5] = {10, 20, 30, 40, 50};

// Declare a pointer and point it to the first element of the array
int* ptr = arr;

// Output the array values using pointer dereferencing
for (int i = 0; i < 5; i++) {
std::cout << "Value at index " << i << " is: " << *(ptr + i) << std::endl;
}

return 0;
}

Explanation:

  • In the example above, int* ptr = arr; makes the pointer ptr point to the first element of the array. In C++, an array’s name itself can be treated as a pointer to its first element.
  • We use pointer arithmetic *(ptr + i) to access the values of each element in the array.

5. Dynamic Memory Allocation Using Pointers

C++ allows you to allocate memory dynamically (i.e., at runtime) using pointers. This is particularly useful when the size of the data is not known at compile time.

Example: Dynamic Memory Allocation

#include <iostream>

int main() {
// Dynamically allocate memory for an integer
int* ptr = new int;

// Assign a value to the dynamically allocated memory
*ptr = 25;

// Output the value
std::cout << "Dynamically allocated value: " << *ptr << std::endl;

// Free the allocated memory
delete ptr;

return 0;
}

Explanation:

  • new int; dynamically allocates memory for an integer, and the pointer ptr holds the address of that memory location.
  • *ptr = 25; assigns a value to the dynamically allocated memory.
  • delete ptr; frees the allocated memory, preventing memory leaks.

6. Pointers to Functions

Pointers can also point to functions, enabling you to call functions indirectly.

Example: Function Pointer

#include <iostream>

// A simple function that takes two integers and returns their sum
int add(int a, int b) {
return a + b;
}

int main() {
// Declare a pointer to the add function
int (*funcPtr)(int, int) = &add;

// Call the function using the pointer
int result = funcPtr(5, 10);

// Output the result
std::cout << "The sum is: " << result << std::endl;

return 0;
}

Explanation:

  • int (*funcPtr)(int, int) = &add; declares a function pointer funcPtr that can point to a function taking two int parameters and returning an int.
  • funcPtr(5, 10); calls the add function using the function pointer.

7. Passing Pointers to Functions

You can pass pointers to functions to manipulate data directly.

Example: Pass-by-Pointer

#include <iostream>

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

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

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

// Call swap by passing pointers to x and y
swap(&x, &y);

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

return 0;
}

Explanation:

  • swap(&x, &y); passes the memory addresses of x and y to the function swap.
  • Inside swap, we use the pointers a and b to manipulate the values directly.

8. Pointers and Classes

In C++, pointers are commonly used with classes, especially when dealing with dynamic memory.

Example: Pointer with Classes

#include <iostream>

class Point {
private:
int x, y;

public:
Point(int a, int b) : x(a), y(b) {}

void display() {
std::cout << "Point(" << x << ", " << y << ")" << std::endl;
}
};

int main() {
// Dynamically allocate memory for a Point object
Point* p = new Point(5, 10);

// Access the display function using the pointer
p->display();

// Free the dynamically allocated memory
delete p;

return 0;
}

Explanation:

  • Point* p = new Point(5, 10); dynamically allocates memory for a Point object and uses the pointer p to access the object.
  • p->display(); calls the display function using the pointer.

Conclusion

In this tutorial, you’ve learned the basics of pointers in C++ and how they can be used for direct memory manipulation, dynamic memory allocation, arrays, function pointers, and class instances. Pointers are a crucial aspect of C++ and understanding them is key to mastering the language.

Scroll to Top