简体   繁体   中英

Passing NULL for array parameter in C/C++

void DoSomeThing(CHAR parm[])
{

}

int main()
{
    DoSomeThing(NULL);
}

Is the passing NULL for array parameter allowed in C/C++?

What you cannot do is pass an array by value. The signature of the function

void f( char array[] );

is transformed into:

void f( char *array );

and you can always pass NULL as argument to a function taking a pointer.

You can however pass an array by reference in C++, and in that case you will not be able to pass a NULL pointer (or any other pointer):

void g( char (&array)[ 10 ] );

Note that the size of the array is part of the type, and thus part of the signature, which means that g will only accept lvalue-expressions of type array of 10 characters

Short answer is yes , you can pass NULL in this instance (at least for C, and I think the same is true for C++).

There are two reasons for this. First, in the context of a function parameter declaration, the declarations T a[] and T a[N] are synonymous with T *a ; IOW, despite the array notation, a is declared as a pointer to T , rather than an array of T . From the C language standard :


...
7 A declaration of a parameter as ''array of type '' shall be adjusted to ''qualified pointer to type '', where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.

The second reason is that when an expression of array type appears in most contexts (such as in a function call), the type of that expression is implicitly converted ("decays") to a pointer type, so what actually gets passed to the function is a pointer value, not an array:


...
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type '' is converted to an expression with type ''pointer to type '' that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

First off, what you're passing to the function is a pointer and not an array . The array notation used for the parm parameter is just syntactic sugar for CHAR *parm .

So yes, you can pass a NULL pointer.

The only issue would be if DoSomeThing were overloaded, in which case the compiler might not be able to distinguish which function to call. But casting to the appropriate type would theoretically fix that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM