If the declaration of an array is visible, one can find its length by dividing its total size by the size of one element:
int squares[4]; int len = sizeof squares / sizeof squares[0];
Because squares
above is
the name of an array, we can
obtain its length using sizeof squares
,
which yields the total size as a number of char
s. sizeof squares[0]
yields the size (in char
s)
of one element, and since all the elements are of the
same size, the ratio of these two sizeof
s is the
number of elements in the array:
void fill_array_with_square_numbers(int *first, int length); int squares[4]; fill_array_with_square_numbers(squares, sizeof squares / sizeof squares[0]);
(For arrays of char
s,
the divisor can be omitted, since sizeof(char)
is defined to be 1
.)
However, this technique doesn't work if the argument
to sizeof
is only a
pointer that happens to point to an element of an array,
rather than an array name. Consider that such a pointer
looks identical to a pointer to a single object, as far
as the compiler is concerned — they don't contain any
information about the length. This is why the example
function above requires the length as a separate
argument: within the function, sizeof first
would
only give the size of a pointer to an integer, not the
length of the array.