An array in C is a fixed-size block of elements of one type, declared as int scores[5]; and accessed by zero-based index, scores[0] to scores[4]. When you pass an array to a function, C hands over only a pointer to the first element, so you must pass the length as a second argument.
How to declare an array in C
Write the element type, the name, and the number of elements in square brackets:
int scores[5];
double prices[100];
char name[32];
An array is a contiguous sequence of objects of one element type, and its size never changes during its lifetime. You can also declare arrays of pointers in the same statement. In float fa[11], *afp[17];, fa is an array of 11 floats and afp is an array of 17 pointers to float.
The declaration alone does not set any values. An array with automatic storage (declared inside a function) holds indeterminate values until you assign them, and using one before that is undefined behavior. An array with static storage duration (declared at file scope, or with static) is zero-initialized.
How to initialize an array
Use a brace-enclosed list:
int a[5] = {1, 2, 3}; /* 1, 2, 3, 0, 0 */
int b[] = {1, 2, 3}; /* size deduced: int[3] */
char s[] = "abc"; /* char[4]: 'a', 'b', 'c', '\0' */
int c[3] = { [2] = 7 }; /* designated initializer (C99): 0, 0, 7 */
Three rules cover most cases:
- Partial lists are zero-filled. Elements you leave out are set to zero, so
int zeros[100] = {0};zeroes the whole array. Since C23 you can also write= {}. - Leave out the size and the compiler counts. With
int b[] = {1, 2, 3};the type is "array of 3 int". Adding an element to the list changes the size with no other edit. - A string literal adds a terminating zero.
char s[] = "abc";has four elements, not three. Forgetting the extra byte is a classic cause of off-by-one overflows when you size achararray by hand.
How to access array elements (indexing)
Indexes start at 0, so an array of N elements has valid indexes 0 to N - 1:
#include <stdio.h>
int main(void) {
int scores[5] = {90, 85, 70, 100, 60};
scores[2] = 75; /* assign */
printf("%d\n", scores[0]); /* read the first element */
for (int i = 0; i < 5; i++) {
printf("scores[%d] = %d\n", i, scores[i]);
}
return 0;
}
Example output:
90
scores[0] = 90
scores[1] = 85
scores[2] = 75
scores[3] = 100
scores[4] = 60
The loop condition is i < 5, not i <= 5. The second form reads scores[5], one element past the end.
Under the hood, E1[E2] is defined to be exactly *((E1)+(E2)). That is why scores[2] and 2[scores] both work and give the same element. You should never write the second form, but it shows that indexing is pointer arithmetic: scores[2] means "the element two positions after the first".
What happens when you go out of bounds
C does not check indexes. The language only defines pointer arithmetic when the original pointer and the result both point at elements of the same array, or one past its end. You may form the one-past-the-end pointer, but you must not dereference it. Anything else, such as scores[10] on a five-element array, or scores - 1, is undefined behavior.
Undefined behavior does not guarantee a crash. The program may print garbage, overwrite a neighboring variable, or seem to work until you change the compiler or the optimization level. If you see a segmentation fault or odd values only sometimes, check loop bounds first.
How to get the length of an array with sizeof
Applied to an array, sizeof gives the total size in bytes. Divide by the size of one element to get the count:
int scores[5] = {90, 85, 70, 100, 60};
size_t count = sizeof scores / sizeof scores[0]; /* 5 */
The result is a size_t, so print it with %zu. The size of int depends on the platform (commonly 4 bytes), which is why you divide instead of hard-coding a number. This idiom only works where the compiler can still see the real array. The next section explains where it stops working.
Why sizeof fails inside a function
In most expressions, an array is implicitly converted to a pointer to its first element. The exceptions are the operands of sizeof and unary &, plus a few others. When you call a function, the array argument is converted, and the parameter is adjusted to a pointer too. These two declarations are the same function:
int sum(int values[5]);
int sum(int *values);
The 5 in the first form is ignored. Inside the function, sizeof values returns the size of a pointer, not of the array. A length that comes out as 1 or 2 instead of the element count is the usual sign of this mistake.
How to pass an array to a function
Pass the array and its length as separate parameters:
#include <stddef.h>
#include <stdio.h>
int sum(const int values[], size_t count) {
int total = 0;
for (size_t i = 0; i < count; i++) {
total += values[i];
}
return total;
}
int main(void) {
int scores[5] = {90, 85, 70, 100, 60};
size_t count = sizeof scores / sizeof scores[0];
printf("%d\n", sum(scores, count));
return 0;
}
Example output: 405.
Three details matter here:
- The function works on the caller's data. It receives a pointer to the same elements, not a copy. Assigning to
values[i]inside the function changes the caller's array. - Use
constfor read-only access.const int values[]makes the parameterconst int *, so the compiler rejects accidental writes. - Compute the length where the array is declared. Do the
sizeofdivision inmain(or wherever the real array lives) and pass the result down.
C99 also lets you promise a minimum size with static: void fadd(double a[static 10], const double b[static 10]). Calling it with an array of five elements is undefined behavior. Compilers may use this promise to warn you, but it does not make the language check anything at run time.
Two-dimensional arrays
A two-dimensional array is an array of arrays, laid out row after row in memory:
int grid[2][3] = { {1, 2, 3}, {4, 5, 6} };
printf("%d\n", grid[1][2]); /* 6 */
When you pass it to a function, only the outermost dimension is adjusted to a pointer. The inner sizes are part of the element type, so the function must know them:
void print_grid(size_t rows, int grid[][3]) {
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < 3; c++) {
printf("%d ", grid[r][c]);
}
printf("\n");
}
}
Here grid[][3] is a pointer to an array of three int. A pointer to an array type as a parameter is not transformed further. If the column count must vary, pass it as a parameter as well and use a variable-length array parameter, which depends on the next topic.
Variable-length arrays and when to avoid them
Since C99, the size may be a run-time value: int a[n];. The size expression is evaluated each time control passes the declaration, and it must be greater than zero. A variable-length array (VLA) cannot be initialized with a brace list, cannot have static storage duration, cannot be at file scope and cannot be a struct member.
Support is optional. In C11 through C22, a compiler that defines __STDC_NO_VLA__ as 1 does not support them, and some compilers disable them by default. If you need a size known only at run time and want portable code, allocate with malloc and free it afterwards, or choose a fixed upper bound.
Common array mistakes in C
- Off-by-one loops. Use
i < count, neveri <= count. - Assigning whole arrays.
b = a;does not compile for arrays. Copy with a loop ormemcpy(b, a, sizeof a), after checking thatbis at least as large. - Comparing with
==.a == bcompares the two pointers, not the contents. Compare element by element, or withmemcmpfor plain data. - Returning a local array. The array ends its lifetime when the function returns, so a pointer to it is dangling. Have the caller supply the buffer instead.
- Floating-point elements. Arrays of
doublefollow the same rules, but comparing the values has its own pitfalls. See double in C: precision and examples.
If you are coming from Python, a C array is closer to the array module than to a list: fixed length, one element type, no built-in length. Python arrays vs lists shows that comparison from the other side.
Frequently asked questions
- Do arrays in C start at 0 or 1?
- Arrays in C start at index 0. An array declared as int a[5] has valid indexes 0 to 4. The expression a[i] is defined as *(a + i), so index 0 is the first element, zero elements past the start.
- How do I get the length of an array in C?
- Inside the scope where the array was declared, divide the total size by the element size: sizeof a / sizeof a[0]. This only works on a real array. Inside a function that received the array as a parameter, the parameter is a pointer, so you must pass the length as a separate argument.
- Does C check array bounds?
- No. Writing a[10] on a five-element array compiles without error in most compilers, but the behavior is defined only while pointers stay inside the array or one past its end. Anything else is undefined behavior, which can crash, corrupt data or appear to work.
- Can I return an array from a function in C?
- Not directly. A function cannot return an array type. You can fill an array the caller passes in, return a pointer to memory allocated with malloc (the caller must free it), or return a struct that contains the array. Never return a pointer to a local array, because it ends its lifetime when the function returns.