Skip to content

Module 5 · Arrays and Strings — topic 1 of 3

Arrays

An array stores a fixed number of elements of one type in contiguous memory. Learn declaration, initialisation, indexing, traversal, passing arrays to functions and why C never checks bounds.

Beginner 17 min read·Lesson 19 of 37 in C Programming

Learning objectives

  • Declare, initialise and traverse one-dimensional arrays
  • Compute an array's length with sizeof
  • Pass arrays to functions and explain array-to-pointer decay

Definition

An array is an object consisting of a contiguous sequence of elements of the same type, accessed by an integer index starting at 0. Its size is fixed when it is created.

Introduction

Storing 60 students' marks in 60 separate variables is impossible to manage. An array gives them one name and a number: marks[0] to marks[59]. Loops can then process all of them with a few lines.

Arrays in C are close to the hardware: elements sit side by side in memory, and a[i] is computed from the starting address plus i times the element size. That makes arrays fast — and makes running off the end dangerous, because C does not check.

Why it matters

Arrays are the foundation of almost every data structure — stacks, queues, heaps, hash tables and matrices are built on them.

Questions on traversal, searching, finding max/min, reversing and counting frequencies appear in every C exam.

Detailed explanation

Declare with a constant size: int marks[5];. Initialise with a brace list: int marks[5] = {70, 82, 65, 90, 58};. Missing initialisers are set to zero, so int counts[26] = {0}; zeroes all 26.

If you omit the size, the compiler counts the initialisers: int primes[] = {2, 3, 5, 7}; has 4 elements. Designated initialisers (C99) set specific positions: int a[10] = {[3] = 7, [9] = 1};.

The number of elements is sizeof arr / sizeof arr[0] — but only where arr is the real array, not a pointer parameter.

When an array is passed to a function it decays to a pointer to its first element. The function receives an address, not a copy, so it can modify the caller's elements, and it cannot find the length itself — pass the length as a separate parameter.

Accessing a[5] in a 5-element array is undefined behaviour. It may read garbage, corrupt another variable or crash. C does not throw an exception.

Index01234
marks[i]7082659058
addressbasebase+4base+8base+12base+16

Syntax

C
type name[SIZE];
type name[SIZE] = {v0, v1, ...};
type name[] = {v0, v1, v2}; /* size from initialisers */
size_t n = sizeof name / sizeof name[0];
void process(int arr[], size_t n); /* same as int *arr */
  • Valid indexes are 0 to SIZE − 1.
  • Arrays cannot be assigned as a whole (a = b; is an error); copy element by element or with memcpy.
  • const int arr[] in a parameter promises the function won't modify the elements.

Code examples

Traverse, sum and find the maximum

C
#include <stdio.h>
int main(void) {
int marks[] = {70, 82, 65, 90, 58};
size_t n = sizeof marks / sizeof marks[0];
int sum = 0, max = marks[0];
for (size_t i = 0; i < n; i++) {
sum += marks[i];
if (marks[i] > max) max = marks[i];
}
printf("n=%zu sum=%d max=%d avg=%.1f\n", n, sum, max, (double)sum / n);
return 0;
}
Output
n=5 sum=365 max=90 avg=73.0

Zero-initialisation and designated initialisers

C
#include <stdio.h>
int main(void) {
int a[6] = {1, 2}; /* rest are 0 */
int b[6] = {[2] = 9, [5] = 4};
for (int i = 0; i < 6; i++) printf("%d ", a[i]);
printf("\n");
for (int i = 0; i < 6; i++) printf("%d ", b[i]);
printf("\n");
return 0;
}
Output
1 2 0 0 0 0
0 0 9 0 0 4

More examples

Functions that work on arrays

C
#include <stdio.h>
void reverse(int arr[], int n) {
for (int i = 0, j = n - 1; i < j; i++, j--) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
void print(const int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d%s", arr[i], i < n - 1 ? ", " : "\n");
}
int main(void) {
int data[] = {4, 8, 15, 16, 23, 42};
int n = (int)(sizeof data / sizeof data[0]);
print(data, n);
reverse(data, n); /* modifies the caller's array */
print(data, n);
int freq[10] = {0};
int digits[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
for (int i = 0; i < 11; i++) freq[digits[i]]++;
for (int d = 0; d < 10; d++)
if (freq[d]) printf("%d appears %d time(s)\n", d, freq[d]);
return 0;
}
Output
4, 8, 15, 16, 23, 42
42, 23, 16, 15, 8, 4
1 appears 2 time(s)
2 appears 1 time(s)
3 appears 2 time(s)
4 appears 1 time(s)
5 appears 3 time(s)
6 appears 1 time(s)
9 appears 1 time(s)

Step-by-step explanation

  • reverse swaps from both ends toward the middle using two indexes in one for (comma operator).
  • Because the array decays to a pointer, reverse changes data in main — no copy is made.
  • print takes const int arr[], documenting and enforcing that it only reads.
  • freq[digits[i]]++ uses each digit as an index into a counting array — a frequency table.
  • Only digits with a non-zero count are printed.

Expected output

Running “Functions that work on arrays” prints exactly:

TextOutput
4, 8, 15, 16, 23, 42
42, 23, 16, 15, 8, 4
1 appears 2 time(s)
2 appears 1 time(s)
3 appears 2 time(s)
4 appears 1 time(s)
5 appears 3 time(s)
6 appears 1 time(s)
9 appears 1 time(s)

Practical applications

  • Audio is an array of samples; images are arrays of pixels.
  • Network buffers are arrays of bytes.
  • Histograms and frequency counts use the counting-array technique.

Best practices

  • Keep the length next to the array — as a constant or a parameter.
  • Loop with i < n, never i <= n.
  • Use const for array parameters a function only reads.

Common mistakes

Using sizeof on an array parameter

Avoid

int count(int arr[]) {
return sizeof arr / sizeof arr[0];
}

Prefer

int count(int arr[], int n) {
return n; /* pass the length in */
}

Inside the function arr is a pointer, so sizeof arr is the size of a pointer (typically 8), not of the array.

Reading past the end

Avoid

int a[3] = {1, 2, 3};
printf("%d\n", a[3]);

Prefer

int a[3] = {1, 2, 3};
printf("%d\n", a[2]);

The last valid index of a 3-element array is 2. a[3] is undefined behaviour.

Assigning arrays

Avoid

int a[3] = {1, 2, 3}, b[3];
b = a;

Prefer

int a[3] = {1, 2, 3}, b[3];
for (int i = 0; i < 3; i++) b[i] = a[i];

Arrays are not assignable in C. Copy the elements with a loop or memcpy(b, a, sizeof a).

Important notes

  • C99 introduced variable-length arrays (int a[n]; with runtime n); C11 made them optional. Large VLAs can overflow the stack; prefer malloc for big or user-sized arrays.
  • Tools such as AddressSanitizer (-fsanitize=address in GCC/Clang) detect out-of-bounds accesses while testing.

Key takeaways

  • Arrays hold a fixed number of same-type elements, indexed from 0.
  • Length = sizeof arr / sizeof arr[0], valid only on the real array.
  • Arrays decay to pointers when passed; pass the length separately. Bounds are never checked.

Try it yourself

  1. 1
    Read 10 integers and print the second-largest distinct value.
  2. 2
    Write a function that rotates an array left by k positions.
  3. 3
    Remove duplicates from a sorted array in place and return the new length.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is the index of the last element of `int a[10];`?
  • BeginnerWhat is printed (int is 4 bytes)?
  • BeginnerAccessing `a[5]` in `int a[5];` causes…
Practise this topic