Home > Mobile >  is it possible to write a function that takes an integer array as argument and returns the number of
is it possible to write a function that takes an integer array as argument and returns the number of

Time:09-29

I know it's possible to calculate the number of the elements of the array by sizeof(the_array)/sizeof(the_array[n]) but I dont know what to do with it if I had to write a function

CodePudding user response:

No, not in the sense you mean.

When an array is used as a function argument, it is automatically converted to a pointer to its first element. The C standard specifies only that this pointer points to the first element of the array, not that it contains any other information about the array. The C standard also does not specify there is any way to obtain the size of the array from the pointer or any other information passed to the function.

If you want a function to know the size of an array, pass the size as a separate argument.

(It is possible a C implementation could provide this information, by including it with the pointer, associating it with the pointer, or storing it before the beginning of the array. I am not aware of any that do, except that debugging features may provide this information.)

CodePudding user response:

It is impossible to pass an object of array type in the argument of a function call (unless the array is embedded as a member of a struct or union type), because the array "decays" to a pointer to its first element (C11 6.3.2.1/3).

Also, any parameter of array type in a function declaration will be automatically adjusted to a pointer type. For example, the declaration int foo(const int bar[5]) is automatically adjusted to int foo(const int *bar) (C11 6.7.5.3/7 or C17 6.7.6.3/7).

It is possible to define a macro to get the length of an array, but it is up to the programmer to ensure that the parameter really is an array and not a pointer:

#define ARRAYLEN(arr) (sizeof (arr) / sizeof *(arr))

For example, it cannot be used on the parameter of a function, even if the function's parameter type looks like an array, because the function's parameter type is really a pointer:

#define ARRAYLEN(arr) (sizeof (arr) / sizeof *(arr))

size_t foo(int bar[5])
{
    return ARRAYLEN(bar); // INCORRECT! bar is a pointer, not an array.
}
  • Related