0

Are char a[] = {'a', '\0'} and char *b = "a" equal?

what is the difference?

gacopu
  • 594
  • 3
  • 21

1 Answers1

5

No they are not equal.

The first create an array of two elements. You can modify the contents of the array as you will (it's mutable).

The second creates a pointer and make it point to the first element of an array containing two elements. The contents of the array that b is currently pointing to is not mutable, you can not change the contents of that array. Literal strings in C are, in essence, read-only. You can however change the pointer b itself, to make it point somewhere else. If you make it point to something which is not a literal string and is not marked const, like for example a, then the contents can be modified.


In memory it would be something like this

For a:

+-----+------+
| 'a' | '\0' |
+-----+------+

The array is a single entity.

And for b:

+---+     +-----+------+
| b | --> | 'a' | '\0' |
+---+     +-----+------+

Here you have two entities, the variable b and the array it points to.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 4
    First mutable, second can't change (UB otherwise). – iBug Jan 14 '19 at 12:18
  • "*is not mutable*" to avoid (upcoming) confusion you might like to point out that the "immutability" does not due to the pointer `b` or its type `char*` but to what the pointer actually points to in this specific example. The same pointer variable may very well point to mutable data. – alk Jan 14 '19 at 12:24