The C sizeof operator yields an object or object type's size in bytes. For an array A, sizeof A divided by sizeof A[0] gives its element count. section 6.1.3 section 12.1
Computing an array length
double values[] = { 1.0, 2.0, 3.0, 4.0 }; size_t count = sizeof values / sizeof values[0]; Here, sizeof values measures the entire array and sizeof values[0] measures one element, so count is 4. section 6.1.3
Key rules:
- Use sizeof(char), which is 1 by definition; objects can be viewed as arrays of unsigned char[sizeof object]. section 12.1
- Write sizeof object with or without parentheses; write sizeof(type) with parentheses. section 12.1
- Do not use sizeof on an array parameter: its innermost dimension is lost when passed to a function. section 6.1.4
Listing 6.1 A function with an array parameter
#include <stdio.h>
void swap_double(double a[static 2]) {
auto tmp = a[0];
a[0] = a[1];
a[1] = tmp;
}
int main(void) {
double A[2] = { 1.0, 2.0, };
swap_double(A);
printf("A[0] = %g, A[1] = %g\n", A[0], A[1]);
}
A small function demonstrates that an array parameter operates directly on the caller's array rather than preserving a complete array object. section 6.1.4
