How to Initialize Array in C: Syntax and Examples
In C, you can initialize an array by specifying its elements inside curly braces using
int arr[] = {1, 2, 3};. You can also declare the size explicitly like int arr[3] = {1, 2, 3}; or initialize all elements to zero with int arr[5] = {0};.Syntax
To initialize an array in C, you use the following syntax:
type arrayName[size] = {value1, value2, ...};- declares an array with a fixed size and initializes it with values.type arrayName[] = {value1, value2, ...};- declares an array where the size is inferred from the number of values.type arrayName[size] = {0};- initializes all elements to zero.
c
int arr1[3] = {1, 2, 3}; int arr2[] = {4, 5, 6, 7}; int arr3[5] = {0};
Example
This example shows how to declare and initialize arrays, then print their elements.
c
#include <stdio.h> int main() { int numbers[4] = {10, 20, 30, 40}; int zeros[5] = {0}; printf("numbers array: "); for (int i = 0; i < 4; i++) { printf("%d ", numbers[i]); } printf("\n"); printf("zeros array: "); for (int i = 0; i < 5; i++) { printf("%d ", zeros[i]); } printf("\n"); return 0; }
Output
numbers array: 10 20 30 40
zeros array: 0 0 0 0 0
Common Pitfalls
Common mistakes when initializing arrays in C include:
- Not specifying enough initial values for the declared size, which leaves some elements uninitialized and may contain garbage values.
- Forgetting to initialize arrays, leading to unpredictable values.
- Using an initializer list larger than the declared size, which causes a compilation error.
Always ensure the number of initial values does not exceed the array size and initialize arrays to avoid garbage data.
c
/* Wrong: initializer list larger than size */ int arr[3] = {1, 2, 3, 4}; // Error /* Right: initializer list fits size */ int arr[4] = {1, 2, 3, 4};
Quick Reference
| Initialization Method | Description | Example |
|---|---|---|
| Fixed size with values | Declare size and initialize with values | int arr[3] = {1, 2, 3}; |
| Size inferred | Let compiler count elements | int arr[] = {4, 5, 6}; |
| Zero initialization | Set all elements to zero | int arr[5] = {0}; |
| Partial initialization | Initialize first elements, rest zero | int arr[5] = {1, 2}; |
Key Takeaways
Initialize arrays using curly braces with values inside.
Array size can be fixed or inferred from initializer list.
Uninitialized elements may contain garbage values; use zero initialization if needed.
Initializer list size must not exceed declared array size.
Partial initialization sets remaining elements to zero automatically.