C++ Pointers

In C++, a pointer is a variable that stores the memory address of another variable. Pointers are powerful tools used for dynamic memory allocation, arrays, functions, and data structures like linked lists.

Pointer Syntax

data_type *pointer_name;

Where:

  • data_type – Type of variable the pointer will point to (e.g., int, float, char).
  • *pointer_name – Declares a pointer variable.

Example: Basic Pointer

#include <iostream>
using namespace std;

int main() {

int num = 10;
int *ptr = &num;// Pointer stores the address of num

cout << "Value of num: " << num << endl;
cout << "Address of num: " << &num << endl;
cout << "Pointer ptr points to: " << ptr << endl;
cout << "Value via pointer: " << *ptr << endl;

return 0;
}

Output

Value of num: 10
Address of num: 0x7ffde2b8a5ac
Pointer ptr points to: 0x7ffde2b8a5ac
Value via pointer: 10

Key Pointer Operations

  • & – Address-of operator: gets the memory address of a variable.
  • * – Dereference operator: accesses the value stored at the memory address.
  • Pointers can be used with arrays, functions, and dynamic memory allocation.

Example: Pointer with Array

#include <iostream>
using namespace std;

int main() {

    int arr[3] = {10, 20, 30};
    int *ptr = arr; // Pointer to the first element of the array

    for(int i = 0; i < 3; i++) {
        cout << "arr[" << i << "] = " << *(ptr + i) << endl;
    }

    return 0;
}

Output

arr[0] = 10
arr[1] = 20
arr[2] = 30

Important Notes

  • Pointers store memory addresses, not the actual values.
  • Dereferencing an uninitialized pointer can lead to undefined behavior.
  • Use pointers carefully with dynamic memory to avoid memory leaks.

Next Topic

Next, learn about Pointer Arithmetic in C++.