How to get the length of an array in C? Is “sizeof” a solution? [duplicate]

Arrays decay to pointers in function calls. It’s not possible to compute the size of an array which is only represented as a pointer in any way, including using sizeof.

You must add an explicit argument:

void show(int *data, size_t count);

In the call, you can use sizeof to compute the number of elements, for actual arrays:

int arr[] = { 1,2,3,4,5 };

show(arr, sizeof arr / sizeof *arr);

Note that sizeof gives you the size in units of char, which is why the division by what is essentially sizeof (int) is needed, or you’d get a way too high value.

Also note, as a point of interest and cleanliness, that sizeof is not a function. The parentheses are only needed when the argument is a type name, since the argument then is a cast-like expression (e.g. sizeof (int)). You can often get away without naming actual types, by doing sizeof on data instead.

Leave a Comment