Common pointer errors - Time & Space Complexity
When working with pointers in C, it's important to see how mistakes can affect program speed.
We want to know how pointer errors impact the number of steps the program takes.
Analyze the time complexity of the following code snippet.
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
printArray(numbers, 5);
return 0;
}
This code prints all elements of an integer array using a pointer.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array elements using pointer arithmetic.
- How many times: The loop runs once for each element in the array (size times).
As the array size grows, the number of steps grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The steps increase directly with the number of elements.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Using pointers always makes the code faster or simpler."
[OK] Correct: Pointer mistakes like wrong addresses or uninitialized pointers can cause errors or slow the program down, not speed it up.
Understanding how pointer errors affect program steps helps you write safer, clearer code and shows you know how to think about program speed.
"What if we changed the pointer to point to a linked list instead of an array? How would the time complexity change?"