Pointers are a unique feature in C++ that allow you to store memory addresses rather than values. They are useful for directly accessing and manipulating memory, enabling efficient data handling and dynamic memory allocation. In this section, we'll cover the basics of pointers, pointer arithmetic, and using pointers with arrays and functions.
Pointer Basics
A pointer is a variable that stores the memory address of another variable. Pointers can be of any type, such as int*
, float*
, or char*
, depending on the data type they point to.
Syntax:
In this example:
number
is a variable with an integer value.ptr
is a pointer that stores the address ofnumber
.*ptr
dereferences the pointer, giving us the value at that address.
Pointer Arithmetic
Pointer arithmetic involves adding or subtracting integer values from a pointer. Pointer arithmetic is particularly useful with arrays, as the pointer to the first element can traverse the entire array by adding or subtracting from it.
Example: Pointer arithmetic with an integer array.
ptr
points to the first element of the array. Using *(ptr + i)
, we access each element by offsetting ptr
by i
positions.Pointer to Arrays
Pointers can also be used to manipulate arrays. When we declare an array, the name of the array is a constant pointer to its first element.
Example: Pointer to an array.
arr
is a pointer to the first element. We access the elements of the array by using pointer arithmetic.Pointers to Functions
Pointers can also point to functions, allowing us to pass functions as arguments, store them in data structures, or assign them dynamically.
Syntax:
In this example:
funcPtr
is a pointer to thegreet
function.- We use
funcPtr()
to call the function through the pointer.
Using Pointers with Arrays in Functions
Pointers are also useful in functions when we want to pass arrays as arguments, as arrays are passed by reference (using their address) rather than by value.
Example: Function that takes a pointer to an array.
Here:
printArray
takes a pointer toint
(int* arr
) and an integersize
.- We pass
numbers
toprintArray
, which iterates and prints each element using the pointer.