Introduction to Pointers
Pointers are variables that store memory addresses of other variables. Instead of holding data directly, they point to the location in memory where the data is stored. Pointers are powerful features in C++ that support dynamic memory management, arrays, strings, functions, and object handling.
Pointers enhance performance and flexibility, especially in systems-level programming, and provide better control over memory.
Declaration and Initialization of Pointers
To declare a pointer, use the asterisk * symbol:
int *ptr;
This means ptr is a pointer to an integer.
To initialize it:
int a = 10;
int *ptr = &a; // & gives address of a
Accessing Values using Pointers
Use the dereference operator * to access the value pointed by a pointer:
cout << *ptr; // prints value of a
Here, *ptr gives the value stored at the address held by ptr.
Pointer Arithmetic
C++ supports arithmetic operations on pointers: ++, –, +, –
Example:
int arr[3] = {10, 20, 30};
int *p = arr;
cout << *p << endl; // 10
cout << *(p + 1) << endl; // 20
Pointer arithmetic moves the pointer to the next element in memory (depends on data type size).
Null Pointer
A null pointer points to nothing. Useful for checking if a pointer is initialized.
int *ptr = nullptr; // modern C++
It prevents accidental access of garbage memory.
Void Pointer
A void* pointer can point to any data type but must be typecast before dereferencing.
void *ptr;
int a = 5;
ptr = &a;
cout << *(int*)ptr; // typecasting required
Used in generic functions and low-level programming.
Wild Pointer
A pointer declared but not initialized is a wild pointer.
int *ptr; // wild pointer
Accessing it leads to undefined behavior. Always initialize pointers.
Dangling Pointer
A pointer pointing to a memory location that has been deallocated or gone out of scope.
int* ptr;
{
int a = 10;
ptr = &a;
} // ‘a’ is now destroyed, ‘ptr’ is dangling
It may crash the program if accessed.