Why pointers are needed in C++ - Performance Analysis
We want to understand why pointers are important in C++ and how their use affects the time it takes for a program to run.
Specifically, we ask: how does using pointers change the number of steps a program needs as the input grows?
Analyze the time complexity of the following code snippet.
void copyArray(int* source, int* destination, int size) {
for (int i = 0; i < size; i++) {
destination[i] = source[i];
}
}
int main() {
int arr1[1000];
int arr2[1000];
copyArray(arr1, arr2, 1000);
return 0;
}
This code copies elements from one array to another using pointers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that copies each element from source to destination.
- How many times: It runs exactly
sizetimes, once for each element.
As the number of elements to copy grows, the number of steps grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 copy steps |
| 100 | 100 copy steps |
| 1000 | 1000 copy steps |
Pattern observation: The work grows directly with the number of items to copy.
Time Complexity: O(n)
This means the time to copy grows in a straight line as the number of elements increases.
[X] Wrong: "Using pointers makes the program run instantly or faster without looping."
[OK] Correct: Pointers help access memory directly, but copying each element still takes time. The loop still runs for every item.
Understanding how pointers affect program steps helps you explain efficient memory use and data handling clearly, a skill useful in many coding discussions.
"What if we changed the copy function to use references instead of pointers? How would the time complexity change?"