-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?

4
  • 2
    Pointers are not arrays. Commented Apr 9, 2022 at 6:58
  • Does this answer your question? stackoverflow.com/questions/15926129/… Commented Apr 9, 2022 at 7:07
  • Adam, do you agree the 1st is a pointer and the 2nd is an array?
    – chux
    Commented Apr 9, 2022 at 7: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. Commented Apr 10, 2022 at 16:18

1 Answer 1

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.

1
  • "if you want this to behave like an array, you then have to malloc space ..." is one way. Others exists, yet the general idea is correct.
    – chux
    Commented Apr 9, 2022 at 7:28

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.