How do you declare and initialize a 1D array in C?
Array declaration: type name[SIZE]; creates a fixed-size contiguous block of memory.
Initialization methods:
int arr[5] = {1, 2, 3, 4, 5};-- explicit values.int arr[5] = {1, 2};-- partial init, rest is zero:{1, 2, 0, 0, 0}.int arr[5] = {0};-- all zeros.int arr[] = {1, 2, 3};-- size deduced from initializer (3 elements).int arr[5];-- uninitialized (garbage values for local arrays).- C99 designated initializers:
int arr[5] = {[2] = 42, [4] = 99};.
Key facts:
- Array size must be a compile-time constant in C89 (VLAs allowed in C99).
- Array indices start at 0.
- No bounds checking -- accessing out-of-bounds is undefined behavior.
- Arrays cannot be assigned to each other:
arr2 = arr1;is illegal.
1. int arr[5]; // uninitialized
2. int arr[5] = {1,2,3,4,5}; // explicit
3. int arr[5] = {0}; // all zeros
4. int arr[] = {1,2,3}; // size = 3 (deduced)
5. int arr[5] = {[2]=42}; // designated init (C99)
6. Access: arr[i], indices 0 to SIZE-1
7. No bounds checking in C
#include <stdio.h>
int main(void) {
/* Full initialization */
int a[5] = {10, 20, 30, 40, 50};
/* Partial: rest is zero */
int b[5] = {1, 2};
/* b = {1, 2, 0, 0, 0} */
/* Size deduced from initializer */
int c[] = {100, 200, 300};
printf("c has %zu elements\n", sizeof(c) / sizeof(c[0])); /* 3 */
/* All zeros */
int d[5] = {0};
/* C99 designated initializers */
int e[5] = {[1] = 10, [3] = 30};
/* e = {0, 10, 0, 30, 0} */
/* Print arrays */
for (int i = 0; i < 5; i++) {
printf("a[%d]=%d b[%d]=%d d[%d]=%d e[%d]=%d\n",
i, a[i], i, b[i], i, d[i], i, e[i]);
}
return 0;
}
- •Array indices start at 0; last valid index is SIZE-1
- •Partial initialization zero-fills remaining elements
- •int arr[] = {...} deduces size from initializer
- •No bounds checking -- out-of-bounds access is UB
- •Arrays cannot be assigned: arr2 = arr1 is illegal
- •Local uninitialized arrays contain garbage values
- •Accessing arr[SIZE] (one past the end) is undefined behavior
- •arr = arr2 does not copy arrays; use memcpy() instead
- •VLAs (int arr[n] where n is a variable) are optional in C11 and not allowed in C89