Address and dereference operators in C++ - Time & Space Complexity
Let's see how using address and dereference operators affects how long a program takes to run.
We want to know how the number of steps changes when we use these operators in code.
Analyze the time complexity of the following code snippet.
int sumArray(int* arr, int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += *(arr + i); // dereference operator
}
return sum;
}
This code adds up all numbers in an array using pointers and the dereference operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array and dereferencing each element.
- How many times: Exactly once for each element in the array (size times).
Each element requires one dereference and addition, so the total steps grow as the array gets bigger.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 dereferences and additions |
| 100 | About 100 dereferences and additions |
| 1000 | About 1000 dereferences and additions |
Pattern observation: The work grows directly with the number of elements.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the array gets bigger.
[X] Wrong: "Using pointers and dereference operators makes the code run faster or slower in a way that changes the overall time complexity."
[OK] Correct: The operators just access data; the number of times you do this depends on the array size, so the time complexity stays the same.
Understanding how pointer operations scale helps you explain your code clearly and shows you know what affects performance.
"What if we used a nested loop to sum elements in a 2D array using pointers? How would the time complexity change?"