3

These are the notations used for 2D Arrays

char (*names)[5] ;

and

char* names[] = {"Jan","Feb"};

and

char names[3][5] = { Initializers..};

I'm getting extremely confused between these notations.

The 1st one declares names to be a pointer to an array of 5 chars i.e

names -> a char pointer -> "Some string"

The 3rd one has a different memory map, i.e it is stored in row major order like a normal array unlike the one stated above.

How is the 2nd notation similar or different from the 1st and 3rd notation.?

Also passing them to functions is a different story altogether. If we declare the 2d array to be of type 2, then it is passed as a double pointer (char** names) while if it is of type 1 or type 3, the columns should be mentioned in the declaration.

Please help me attain more clarity over these issues. Thanks.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Hooli
  • 711
  • 2
  • 13
  • 24
  • 1
    possible duplicate of [C pointer to array/array of pointers disambiguation](http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation) – P.P Aug 20 '13 at 19:36
  • 1
    Read: [Difference between `char* str[]` and `char str[][]` and how both stores in memory?](http://stackoverflow.com/questions/17564608/what-does-the-array-name-mean-in-case-of-array-of-char-pointers/17661444#17661444) I explained with diagrams. – Grijesh Chauhan Aug 20 '13 at 19:49

1 Answers1

6

Only one of those examples is a 2D array:

char names[3][5];

The others are different:

char (*names)[5] ;

is a pointer to a 1D array, and:

char* names[] = {"Jan","Feb"};

is a 1D array of pointers.

I'm going to rename them now to be clearer:

char a[3][5];
char (*b)[5];
char *c[3];

a is the only real two dimensional array. That is, it occupies contiguous memory and has room for three strings, each 5 characters long (including null terminator).

b is a pointer to an array; no storage for any potential contents of that array is included.

c is an array of pointers, each can be used to point to any string you happen to care about; no storage is reserved for any of the strings themselves, just for the three pointers.

If you have a function with a prototype like:

void myfunction(char **p);

Only c can be passed to this function; the others won't behave the way you'd like them to.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • 3
    Additionally, the array of 5 `char` that `b` points to may be an element of an array of arrays of 5 `char`, so it `b` be used access a two-dimensional array. `b = a` is a legal assignment. – Eric Postpischil Aug 20 '13 at 20:16