Reputation: 83
consider the following code:
#define MAX_COUNT 4
static int foo(int w[MAX_COUNT])
{
int *p = w;
if (w) {
w[0] = 10; w[1] = 20; w[2] = 30; w[3] = 40;
}
return 0;
}
is it portable and legal pass NULL to above defined foo() (for example, for a situation when I don't need w[] be altered)? Given that the name of an array is a pointer to its first element, it seems to me that it should be OK, but perhpas I'm missing something?
Thanks !
Upvotes: 1
Views: 208
Reputation: 78903
C99 has the construct with the awfull syntax (for your example)
static int foo(int w[static MAX_COUNT]);
which basically means that the function expects at least MAX_COUNT
elements. Calling such a function with NULL would then be considered
as an error.
Unfortunately this feature is not yet widely implemented. e.g gcc
and clang
just accept the syntax but don't do anything useful with the
information.
Upvotes: 1
Reputation: 355049
In C, an array type function parameter is the same as a pointer type, so the following are the same:
static int foo(int w[]);
static int foo(int* w);
So, yes, it is legal to pass NULL
to this function.
Given that the name of an array is a pointer to its first element
Not quite. An array decays to a pointer to its initial element under most circumstances, the exceptions being when it is the operand of sizeof
or the unary &
operator (the address-of operator).
Upvotes: 4
Reputation: 127428
It should be fine. The number of elements in the array that you passed are merely a formalism, and not really needed. w
is just a pointer to int
. There is no other runtime or compilation check.
Upvotes: 1