Using Pointers
COS2611 - Programming: Data Structures · Dynamic Memory Allocation
Using Pointers
Pointers are a fundamental concept in C++ that allow you to directly access and manipulate memory. A pointer is a variable that stores the memory address of another variable. This is useful for dynamic memory allocation, which is the process of allocating memory during runtime.
Declaring Pointers
To declare a pointer, you use the asterisk (*) symbol. The syntax for declaring a pointer is:
data_type *pointer_name;For example, to declare a pointer to an integer:
int *ptr;This statement creates a pointer named ptr that can point to an integer variable.
Assigning Addresses to Pointers
To assign an address to a pointer, you use the address-of operator (&). This operator gives the memory address of a variable. For example:
int num = 10; // Declare an integer variable
int *ptr; // Declare a pointer
ptr = # // Assign the address of num to ptrAfter this code is executed, ptr points to the memory location of num.
Dereferencing Pointers
Dereferencing a pointer means accessing the value stored at the address the pointer is pointing to. You use the asterisk (*) operator to dereference a pointer. For example:
int value = *ptr; // Get the value at the address stored in ptrIn this case, value will be set to 10, the value of num.
Remember: Always ensure that a pointer is pointing to a valid memory address before dereferencing it. Dereferencing a null or invalid pointer can lead to undefined behaviour.
Dynamic Memory Allocation
C++ provides the new and delete operators for dynamic memory allocation and deallocation. The new operator allocates memory for a variable or an array during runtime. The syntax is:
pointer_name = new data_type;For example, to allocate memory for an integer:
int *ptr = new int;This line allocates memory for a single integer and assigns the address of that memory to ptr.
Allocating Arrays Dynamically
You can also dynamically allocate an array using the new operator. The syntax is:
pointer_name = new data_type[size];For example, to allocate an array of 5 integers:
int *arr = new int[5];This allocates memory for an array of 5 integers. You can access the elements using pointer arithmetic or array indexing:
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;Deallocating Memory
It is important to free the dynamically allocated memory when it is no longer needed to prevent memory leaks. You use the delete operator for this purpose. For a single variable, the syntax is:
delete pointer_name;For example:
delete ptr;For an array, use:
delete[] pointer_name;For example:
delete[] arr;Watch out: Do not use delete on a pointer that was not allocated with new. This can lead to undefined behaviour.
Pointer Arithmetic
Pointer arithmetic allows you to perform arithmetic operations on pointers. For example, if you have a pointer to an integer array, you can increment the pointer to access the next element:
int *ptr = arr;
ptr++; // Now ptr points to arr[1]Each increment moves the pointer to the next integer in memory, which is typically 4 bytes ahead (assuming an integer is 4 bytes).
Null Pointers
A null pointer is a pointer that does not point to any valid memory location. You can assign a pointer to nullptr to indicate that it is not currently pointing to anything:
int *ptr = nullptr;Using null pointers can help prevent dereferencing invalid memory. Always check if a pointer is null before dereferencing it.
Tip: Use null pointers to initialise pointers when you declare them. This practice helps avoid undefined behaviour from uninitialised pointers.
Function Pointers
Pointers can also point to functions. This allows you to pass functions as arguments to other functions. The syntax for declaring a function pointer is:
return_type (*pointer_name)(parameter_types);For example, to declare a pointer to a function that takes two integers and returns an integer:
int (*func_ptr)(int, int);You can assign a function to this pointer:
int add(int a, int b) {
return a + b;
}
func_ptr = add;You can then call the function using the pointer:
int result = func_ptr(2, 3); // result is now 5Common Mistakes with Pointers
Watch out: A common mistake is forgetting to free dynamically allocated memory. Always use delete or delete[] for memory allocated with new to avoid memory leaks.
Watch out: Another mistake is dereferencing a pointer that has not been initialised or has been set to null. Always check your pointers before dereferencing them.
Summary
- A pointer is a variable that stores the address of another variable.
- Use the address-of operator (&) to assign an address to a pointer.
- Dereference a pointer using the asterisk (*) operator.
- Use
newto allocate memory dynamically anddeleteto free it. - Pointer arithmetic allows you to navigate through memory locations.
- Always check for null pointers before dereferencing.
Check your understanding
- What is a pointer in C++?
- How do you assign a memory address to a pointer?
- What is the purpose of the
deleteoperator? - How can you use pointers to pass functions as arguments in C++?