An array is a block of memory holding n elements of the same type. Element i lives i * sizeof(element) bytes after the first, so indexing starts at 0. The array name is not a variable you can assign to; in most expressions it converts to a pointer to its first element.
Remember
type name[size];
int scores[5]; /* 5 ints, indexes 0..4 */
scores[0] = 90; /* first element */
scores[4] = 75; /* last element */
Reference
Cheat Sheet
Keep these facts handy while you work with Array Basics in C.
#include <stdio.h>
int main(void) {
int temps[5];
for (int i = 0; i < 5; i++) {
temps[i] = 20 + i * 2;
}
for (int i = 0; i < 5; i++) {
printf("temps[%d] = %d\n", i, temps[i]);
}
printf("total bytes: %zu\n", sizeof temps);
return 0;
}
Check these before relying on Array Basics in real programs.
off
Off-by-one
An array of size 5 has no a[5]. Use i < 5, not i <= 5.
uninit
Uninitialized elements
A local array holds garbage until you set it. Initialize with = {0}.
Remember
Key Takeaways
Same type: every element matches.
Index: starts at zero.
Memory: one contiguous block.
One line: An array is a block of memory holding n elements of the same type.
Frequently Asked Questions
The index is an offset from the first element. The first element is zero elements away from the start, so its index is 0.
Local arrays live on the stack, global and static arrays in static storage, and malloc-allocated arrays on the heap.
Continue with "C Declaration and Initialization" next. Declare arrays with a size and initialize them with braces or designated indexes. The C Arrays hub lists every topic in order.