-1

In C, why can't I write:

char **expectedPINs01 = { "0", "5", "7", "8", "9" };

Cause I got:

warning: initialization of ‘char **’ from incompatible pointer type ‘char *’

But it is possible to write:

char *expectedPINs01[] = { "0", "5", "7", "8", "9" };

What's the difference?

Adam
  • 7
  • 4
  • 2
    Pointers are not arrays. – embeddedstack Apr 09 '22 at 06:58
  • Does this answer your question? https://stackoverflow.com/questions/15926129/char-vs-char-c-for-accessing-a-string-array – embeddedstack Apr 09 '22 at 07:07
  • Adam, do you agree the 1st is a _pointer_ and the 2nd is an _array_? – chux - Reinstate Monica Apr 09 '22 at 07:26
  • In my view, there isn't really such a thing as an array in C. There are pointers, and there are different ways of allocating memory. [] is a shorthand in declarations for allocating space, and [] in expressions is a shorthand for pointer arithmetic. That's why for example `printf("%c\n", 1["hello"]);` compiles with no complaints even with `-Wall` and prints `e\n`. The number `1` is obviously not an "array", yet the [] shorthand happily does its work and produces 1 plus the address of the `h` to yield `e`. – Alex Nicolaou Apr 10 '22 at 16:18

1 Answers1

2

When you write char ** you are getting enough space for one pointer. If you want this to behave like an array, you then have to malloc space sufficient for the size of the array and fill in the entries.

When you write char *x[5] you get enough space for 5 pointers.

When you use the initialization shorthand, you can omit the 5 because the compiler can see from your initializer that you want there to be space for 5 pointers, and it reserves enough space for them and then uses the initializer shorthand to fill them in for you.

Alex Nicolaou
  • 217
  • 1
  • 4