C ยท Chapter 17 of 45

C Arrays

An array is a collection of elements of the same type stored in contiguous memory. Each element is accessed using an index, starting at 0 for the first element.

Arrays have a fixed size determined at declaration time, and C does not automatically check whether an index is within bounds, so care is needed to avoid reading or writing outside the array.

Syntax
type name[size] = {values};

Declaring and initializing

You can declare an array with a fixed size like `int nums[5];`, or initialize it directly with values like `int nums[] = {1, 2, 3};`, letting the compiler infer the size.

Accessing elements

Elements are accessed with square-bracket indexing, such as `nums[0]` for the first element. Indexes range from 0 to size minus 1.

Example 1 (c)
#include <stdio.h>

int main() {
  int nums[3] = {10, 20, 30};
  printf("%d\n", nums[1]);
  return 0;
}
Output
20

nums[1] accesses the second element (index starts at 0), which is 20.

Example 2 (c)
#include <stdio.h>

int main() {
  int nums[4] = {1, 2, 3, 4};
  for (int i = 0; i < 4; i++) {
    printf("%d ", nums[i]);
  }
  printf("\n");
  return 0;
}
Output
1 2 3 4 

A for loop is a common way to iterate through every element of an array.

Key points

  • Array indexing starts at 0.
  • All elements of an array share the same data type.
  • C does not check array bounds automatically.
  • Array size is fixed once declared (unless using dynamic memory).
๐Ÿ’ก Note: Accessing an index outside the array's bounds is undefined behavior and a frequent source of bugs.

๐Ÿ“ Quick Quiz

1. What is the index of the first element in a C array?

2. What happens if you access an out-of-bounds index?

3. Can an array in C hold mixed types?