C Arrays Introduction
In this page:
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?
#include <stdio.h>
int main() {
int numbers[3] = {10, 20, 30};
printf("%d", numbers[0]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int nums[] = {1, 2, 3};
printf("%d", nums[2]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("%d", arr[2]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
arr[1] = 99;
printf("%d", arr[1]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: