Nearby lessons
53 of 124C - Array Declaration
How to declare an array in C — the type name[size] syntax, the rules for the size expression, declaring several arrays at once, and what an uninitialised array actually contains.
The Declaration Syntax
An array declaration has exactly three parts:
| Part | Example | Meaning |
|---|---|---|
| Data type | int | What kind of value each element holds |
| Array name | marks | Any valid identifier |
| Size in brackets | [5] | How many elements to reserve |
Rules for the Size
In classic C the size must be known when the program is compiled, because the compiler has to reserve the exact number of bytes:
Using a Variable as the Size
Since C99, a local array may be sized by a variable — this is called a variable length array (VLA). It works on most compilers, but it is optional in C11 and cannot be initialised with a list:
Prefer #define or const
Writing the size in one place means you change it in one place. Compare these two versions:
Declaring Several Arrays Together
Arrays of the same type can share one declaration, and you can mix arrays with ordinary variables:
What Is Inside an Undeclared-Value Array?
Declaring an array reserves the bytes but does not clear them. A local array starts out holding whatever was left in that memory:
Common Mistakes
- Using the size as an index —
int a[5];thena[5] = 1;writes out of bounds. - Empty brackets without an initialiser —
int a[];is an error; the compiler cannot guess the size. - Assuming locals start at zero — they do not. Initialise before you read.
- Declaring a huge array as a local —
int big[10000000];overflows the stack and crashes. Large arrays belong in global scope or on the heap.
int marks[5]; — not int[5] marks;. The second form is Java or C#, and it will not compile in C.- Syntax: dataType arrayName[size];
- The size must be a positive integer constant, not a variable.
- Use #define or const for the size to avoid magic numbers.
- An uninitialised local array contains garbage values.
- Declaring an array reserves size * sizeof(type) bytes.