← Back to C Course | Chapter 6: Arrays & Strings | Lesson 1 of 8

C Arrays Introduction

What is an Array?

Because all elements sit in one contiguous memory block, the compiler can compute any element's address instantly from the array's starting address and the element's index, which is what makes array access O(1) rather than requiring a search.

Example: What is an Array?

c
#include <stdio.h>
int main() {
	int numbers[3] = {10, 20, 30};
	printf("%d", numbers[0]);
	return 0;
}

Declaring and Initializing Arrays

The number of values inside the braces determines the array's size if you omit it explicitly, e.g. int nums[] = {1,2,3} creates an array of exactly 3 elements. Leaving elements uninitialized when a size is given leaves them with unpredictable garbage values, not zero.

Example: Declaring and Initializing Arrays

c
#include <stdio.h>
int main() {
	int nums[] = {1, 2, 3};
	printf("%d", nums[2]);
	return 0;
}

Accessing Array Elements

C performs no bounds checking, so reading or writing arr[10] on a 5-element array compiles fine but corrupts nearby memory or crashes at runtime -- always keep track of an array's declared size separately if you need to check bounds yourself.

Example: Accessing Array Elements

c
#include <stdio.h>
int main() {
	int arr[5] = {1, 2, 3, 4, 5};
	printf("%d", arr[2]);
	return 0;
}

Modifying Array Elements

Assigning to arr[i] = value overwrites only that single memory slot; the rest of the array is untouched. This is how you build up array contents incrementally, such as filling an array with user input one entry at a time inside a loop.

Example: Modifying Array Elements

c
#include <stdio.h>
int main() {
	int arr[3] = {1, 2, 3};
	arr[1] = 99;
	printf("%d", arr[1]);
	return 0;
}

Looping Through Arrays

A typical traversal loop runs from index 0 to size-1 inclusive -- looping to i <= size instead of i < size is one of the most common off-by-one bugs in C, since it reads one element past the array's actual bounds.

Example: Looping Through Arrays

c
#include <stdio.h>
int main() {
	int arr[5] = {1, 2, 3, 4, 5};
	for (int i = 0; i < 5; i++) {
		printf("%d ", arr[i]);
	}
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.