R-Rothrock
R-Rothrock

Reputation: 427

char** v *char[] in C

As I read through C code, I often times see this:

int main(int argc, char **argv)

but I always learned to do this:

int main(int argc, char *argv[])

So, why would I use one over the other? I know they're technically different, but I don't see quite why I'd use one as opposed to the other.

Thanks in advance.

Upvotes: 1

Views: 175

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

From the C Standard (6.7.6.3 Function declarators (including prototypes)):

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.

So these declaration of main:

int main(int argc, char **argv)

and

int main(int argc, char *argv[])

are equivalent. If to exclude main that shall be declared only once you may declare the same function twice, like for example:

void f( char * [] );

and:

void f( char ** );

in the same translation unit. Moreover you even can declare the above function like

void f( char * [10] );

or

void f( char * [100] );

because in any case a parameter having an array type is adjusted by the compiler to a pointer to the element type like

void f( char **  );

The same approach is used for parameters that have function types.

For example these two function declarations:

void f( void ( void ) );

and:

void f( void ( * )( void ) );

are equivalent because function parameters having function types are adjusted by the compiler to pointer types to the function types.

From the C Standard:

8 A declaration of a parameter as "function returning type" shall be adjusted to "pointer to function returning type", as in 6.3.2.1.

Upvotes: 2

Seva Alekseyev
Seva Alekseyev

Reputation: 61388

Functionally, for the purposes of access to the arguments, those two notations are equivalent.

The [] notation may have a marginal benefit of distinguishing between a pointer to a single element and a pointer to an array; the char** can be misread as an out-parameter of type char*.

Unlikely with main()'s argv though.

Upvotes: 3

Related Questions