2

When I declare an array in C:

char a[] = "something";

I understand that a is implicitly a const character pointer, i.e. a is of the type: (char * const)

But then why does the following statement result in the compiler warning about incompatible pointer types?

char * const * j = &a;

The only way I've managed to get rid of it is by explicitly casting the right hand side to (char * const *).

I hypothesized that & operator returns a constant pointer and tried:

char * const * const j = &a;

without success.

What is going on here?

Akay
  • 225
  • 2
  • 8
  • 2
    `a` is not a pointer, it's an array. In some situations, it will "decay" to a pointer to `a[0]`, or a `char *`... but `&a` does not give the address of a pointer, it gives the address of the array... which is the same address as `&a[0]`, but a different *type*, as it points to an array and not to a `char`. `char * const * const j` is a pointer to a pointer, which `&a` is not. – Dmitri Mar 22 '17 at 00:05

1 Answers1

4
char a[] = "something";

I understand that a is implicitly a const character pointer, i.e. a is of the type: (char * const)

Wrong, a is of type (non-const) char[10].

So now that we know a is char[10], it's clear why the following doesn't compile:

char * const * j = &a;

&a is of type char(*)[10] (i.e. pointer to char[10]). char(*)[10] and char * const * are completely unrelated.


If you wrote char* a = "something";, then a would be a char*.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Then does `char * const k = a;` convert silently? – Akay Mar 22 '17 at 00:08
  • 1
    Yes, that is known as [array-to-pointer decay](http://stackoverflow.com/q/1461432/3425536). – Emil Laine Mar 22 '17 at 00:09
  • Oh..that explains. I thought array and pointer were internally represented the same way. – Akay Mar 22 '17 at 00:11
  • Ah not at all. A pointer is represented as an integer, whereas an array is represented as a sequence of objects. – Emil Laine Mar 22 '17 at 00:13
  • Hmmm...so after all the checks are done on compilation; at run time, are the array access operations just doing pointer arithmetic? Or is there something more to it? Or is that left up to the compiler? – Akay Mar 22 '17 at 00:18