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?

1
  • 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. Commented Mar 22, 2017 at 0:05

1 Answer 1

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*.

Sign up to request clarification or add additional context in comments.

5 Comments

Then does char * const k = a; convert silently?
Yes, that is known as array-to-pointer decay.
Oh..that explains. I thought array and pointer were internally represented the same way.
Ah not at all. A pointer is represented as an integer, whereas an array is represented as a sequence of objects.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.