0
0
Cprogramming~5 mins

Storage size overview in C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Storage size overview
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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).
How Execution Grows With Input

Memory size grows as we add more elements or bigger types.

Input Size (array length)Approx. Memory Used
10Size of 10 ints + other variables
100Size of 100 ints + other variables
1000Size of 1000 ints + other variables

Pattern observation: Memory grows linearly with the number of array elements.

Final Time Complexity

Space Complexity: O(n)

This means memory size grows in direct proportion to the number of elements we store.

Common Mistake

[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.

Interview Connect

Understanding how memory size grows helps you write programs that use memory wisely and avoid surprises in real projects.

Self-Check

"What if we changed the array to hold doubles instead of ints? How would the memory size change?"