Are char a[] = {'a', '\0'}
and char *b = "a"
equal?
what is the difference?
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.