How to Declare Array in C: Syntax and Examples
In C, you declare an array using the syntax
type name[size]; where type is the data type, name is the array's name, and size is the number of elements. For example, int numbers[5]; declares an integer array with 5 elements.Syntax
An array declaration in C has three parts:
- type: The data type of the elements (e.g.,
int,char). - name: The identifier you choose for the array.
- size: The number of elements the array will hold, written inside square brackets.
The general form is: type name[size];
c
int numbers[5]; char letters[10]; float prices[3];
Example
This example shows how to declare an integer array, assign values, and print them using a loop.
c
#include <stdio.h> int main() { int numbers[5]; // Assign values to the array for (int i = 0; i < 5; i++) { numbers[i] = (i + 1) * 10; } // Print the array elements for (int i = 0; i < 5; i++) { printf("numbers[%d] = %d\n", i, numbers[i]); } return 0; }
Output
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Common Pitfalls
Common mistakes when declaring arrays in C include:
- Forgetting to specify the size (except when initializing immediately).
- Using a size of zero or negative numbers (not allowed).
- Accessing elements outside the declared size (causes undefined behavior).
- Confusing array declaration with pointer declaration.
Example of wrong and right declaration:
c
// Wrong: size missing // int arr[]; // Error: size required without initialization // Right: size specified int arr[3]; // Or initialize with size inferred int arr2[] = {1, 2, 3};
Quick Reference
| Concept | Example | Notes |
|---|---|---|
| Declare int array of 5 | int arr[5]; | Creates array with 5 integers |
| Declare char array | char name[10]; | Can hold 10 characters |
| Initialize array | int nums[3] = {1, 2, 3}; | Size inferred if omitted |
| Access element | arr[0] = 10; | Index starts at 0 |
| Invalid size | int bad[-1]; | Negative size not allowed |
Key Takeaways
Declare arrays with
type name[size]; specifying data type and size.Array size must be a positive integer and known at compile time.
Access array elements using zero-based indexing from 0 to size-1.
You can initialize arrays at declaration to avoid specifying size explicitly.
Avoid accessing elements outside the declared size to prevent errors.