Pointers

Piyush AgrawalPiyush Agrawal
2 min read

Pointers are a powerful feature in C++ that allow you to work with memory directly. A pointer is a variable that holds the memory address of another variable. Here's a basic overview of pointers in C++:

int number = 10;
int *ptr;  // Declaration of a pointer to an integer

ptr = &number;  // Initialization: ptr now holds the address of 'number'

Accessing Value through a Pointer:

int value = *ptr;  // Dereferencing the pointer to get the value stored at the memory location it points to

Pointer Arithmetic:

int array[5] = {1, 2, 3, 4, 5};
int *arrPtr = array;

// Accessing elements using pointer arithmetic
int secondElement = *(arrPtr + 1);  // This is equivalent to array[1]

Dynamic Memory Allocation:

int *dynamicPtr = new int;  // Allocating memory for an integer dynamically
*dynamicPtr = 20;           // Assigning a value to the dynamically allocated memory

// Don't forget to free the memory to avoid memory leaks
delete dynamicPtr;

Pointers and Functions:

void modifyValue(int *ptr) {
    *ptr = 100;
}

// Usage
int main() {
    int variable = 42;
    modifyValue(&variable);  // Pass the address of 'variable' to the function
    // 'variable' is now modified to 100
    return 0;
}

Null Pointers:

int *nullPtr = nullptr;  // C++11 and later
// or
int *nullPtr = NULL;     // Prior to C++11

Pointers and Arrays:

int numbers[5] = {1, 2, 3, 4, 5};
int *arrPtr = numbers;

// Accessing array elements through a pointer
int thirdElement = *(arrPtr + 2);  // This is equivalent to numbers[2]

References vs. Pointers:

int value = 42;
int &ref = value;   // Reference
int *ptr = &value;  // Pointer

// Both can be used to modify 'value'
ref = 100;          // Same as modifying through pointers: *ptr = 100;

Pointers in C++ provide a way to work with memory at a lower level, and they are often used in scenarios involving dynamic memory allocation, arrays, and functions that need to modify variables outside their scope. However, improper use of pointers can lead to memory-related issues, so caution is required when working with them.

0
Subscribe to my newsletter

Read articles from Piyush Agrawal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Piyush Agrawal
Piyush Agrawal