Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C difference between *[] and **

Tags:

arrays

c

pointers

This might be a bit of a basic question, but what is the difference between writing char * [] and char **? For example, in main,I can have a char * argv[]. Alternatively I can use char ** argv. I assume there's got to be some kind of difference between the two notations.

like image 760
user472875 Avatar asked Nov 17 '10 19:11

user472875


2 Answers

Under the circumstances, there's no difference at all. If you try to use an array type as a function parameter, the compiler will "adjust" that to a pointer type instead (i.e., T a[x] as a function parameter means exactly the same thing as: T *a).

Under the right circumstances (i.e., not as a function parameter), there can be a difference between using array and pointer notation though. One common one is in an extern declaration. For example, let's assume we have one file that contains something like:

char a[20];

and we want to make that visible in another file. This will work:

extern char a[];

but this will not:

extern char *a;

If we make it an array of pointers instead:

char *a[20];

...the same remains true -- declaring an extern array works fine, but declaring an extern pointer does not:

extern char *a[]; // works

extern char **a;   // doesn't work
like image 160
Jerry Coffin Avatar answered Sep 30 '22 06:09

Jerry Coffin


Depends on context.

As a function parameter, they mean the same thing (to the compiler), but writing it char *argv[] might help make it obvious to programmers that the char** being passed points to the first element of an array of char*.

As a variable declaration, they mean different things. One is a pointer to a pointer, the other is an array of pointers, and the array is of unspecified size. So you can do:

char * foo[] = {0, 0, 0};

And get an array of 3 null pointers. Three char*s is a completely different thing from a pointer to a char*.

like image 35
Steve Jessop Avatar answered Sep 30 '22 06:09

Steve Jessop