Vilhelm Gray Vilhelm Gray - 9 months ago 52
C Question

Is there a difference between const char * const and const char []?

Consider the two following lines of code:

const char *ptr = "Hello";
char arr[] = "Hello";

For the pointer definition, the
string literal is essentially immutable, but the
variable itself can change and hold a different address.

For the array definition, the
string literal is copied to the location of the array, but
cannot point to a different location; however, the string held by the array is mutable and thus can be changed.

Now consider the following two lines of code:

const char * const ptr = "Hello";
const char arr[] = "Hello";

Here, both strings are immutable as a result of the
const char
qualifier -- more interesting though: with
defined as a constant pointer, it cannot point to a different address.

Would these two lines of code result in the same behavior? If the end effect is the same, is there a theoretical difference in implementation -- for example, does the pointer method allocate memory for an anonymous array to hold the string in addition to the pointer itself, while the array method only allocates memory for an array?

Answer Source

Here's a few differences.

First off, this may hold true on certain implementations as the pointers can point to the same memory:

const char * const ptr1 = "Hello";
const char * const ptr2 = "Hello";

ptr1 == ptr2;

But it cannot be true using the array form.

Anyway, the real difference is that their types are different. In particular, the char[] version retains its size in the array type. So sizeof(arr) gives you the size of the array, rather than a pointer, and you can also create pointers to arrays to arr.