Storage size overview in C - Time & Space Complexity
When we talk about storage size in C, we want to understand how much memory different data types use.
This helps us know how the program's memory needs grow as we use more or bigger data.
Analyze the memory size used by different variables in this code snippet.
#include <stdio.h>
int main() {
int a;
double b;
char c;
int arr[10];
return 0;
}
This code declares variables of different types and an array, each using some memory space.
Here, we look at how memory size adds up for each variable and array element.
- Primary operation: Counting memory size of each variable and array elements.
- How many times: Once per variable, and once per array element (10 times for the array).
Memory size grows as we add more elements or bigger types.
| Input Size (array length) | Approx. Memory Used |
|---|---|
| 10 | Size of 10 ints + other variables |
| 100 | Size of 100 ints + other variables |
| 1000 | Size of 1000 ints + other variables |
Pattern observation: Memory grows linearly with the number of array elements.
Space Complexity: O(n)
This means memory size grows in direct proportion to the number of elements we store.
[X] Wrong: "All variables use the same amount of memory regardless of type or size."
[OK] Correct: Different types like int, double, and char use different amounts of memory, and arrays multiply that by their length.
Understanding how memory size grows helps you write programs that use memory wisely and avoid surprises in real projects.
"What if we changed the array to hold doubles instead of ints? How would the memory size change?"