Doing
char c = "c"
is wrong, "c"
is an array which contains one element and a null termination, the first element is 99, also called 'c'
. For eg.
char ab[2] = "ab"
Here, "ab"
is equivalent to {'a', 'b', '\0'}
The '\0' at the end is explained below. "c"
is equivalent to {'c', '\0'}
and arrays generally point to the first element of the array. So, in your code c
actually points to an array, whose first element is c
. So the pointer to that array also points to 'c'.
char c = *"c"
actually works but is bad. You could also change the printf
to printf("%c\n", *c)
if c
were a pointer, deferencing c
will give you the first element of the array and c
is the first and element.
You should do
char c = 'c'
And the null termination of strings is because:
"c"
or any other string is actually {'c', '\0'}
with a null termination at the end. It's need so that we can know when a string ends. For eg.
In "abcdefgh"
, we would have no idea when the string ended, the user would have to know how long each string is plus how long the buffer is, so it is terminated by a '\0'
at he end and the string is stopped to be parsed when '\0'
is reached.
So, "abcdefgh"
is actually {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0'}
.