Size
Tags: #◇CCPROG2 #◇C Programming #◇Programming #◇Computer Science #◇Data Structures #◇Data Types #◇Structured Programming #◇Memory Management
◇Overview
The size of an array is the number of elements it can hold, determined at declaration and fixed for the array’s lifetime.
◇Key Concepts
Array size must be a positive integer constant (before C99) C99+ allows Variable-Length Arrays (VLAs) with runtime size sizeof(arr) / sizeof(arr[0]) gives the element count There is no built-in bounds checking
◇Details / Theory
Compile-Time Size
#define N 100
int arr[N]; // Size = 100 (constant expression)
int arr2[5]; // Size = 5 (literal)
Computing Size at Runtime
int arr[10];
int count = sizeof(arr) / sizeof(arr[0]); // count = 10
This only works when
arris a true array, not a pointer.
Variable-Length Arrays (VLAs — C99)
int n;
scanf("%d", &n);
int arr[n]; // Size determined at runtime
VLAs are allocated on the stack and cannot be initialized with {...}.
Size and Memory
Total memory = size × sizeof(element_type):
| Declaration | Elements | Total Bytes (typical) |
|---|---|---|
int arr[10] | 10 | 40 |
char str[20] | 20 | 20 |
double vals[5] | 5 | 40 |
Size in Functions
When an array is passed to a function, it decays to a pointer, so sizeof no longer works. Always pass the size as a separate parameter:
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
}
◇Common Pitfalls
Using sizeof(arr) on a function parameter — gives pointer size, not array size. Off-by-one: accessing arr[size] when valid indices are 0 to size - 1. Forgetting that VLAs cannot be initialized with {...}.
◇Summary
TL;DR — Array size is the number of elements, fixed at declaration. Use
sizeof(arr)/sizeof(arr[0])for element count. Always pass size separately to functions since arrays decay to pointers.
◇Links
Related: ◇Declaration — ◇Element Type — ◇Accessing Elements — ◇Name — ◇Arrays and Functions Source / Reference:
◇References & Navigation
- Previous Topic: ◇Dimension
- Next Topic: ◇Declaration
- Related Notes: ◇Characteristics & Attributes, ◇Memory Allocation
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
Which operator can be used to determine the total memory size in bytes occupied by an array?
How can you calculate the number of elements in a locally declared array arr?
What is a strict requirement regarding the size of a standard array during its declaration in C89?