I am having trouble understanding why a character pointer is able to hold a string.
Shouldn't it be like character, only should be able to hold a character.
Picture:
+---+---+---+----+------
| A | B | C | \0 | ???
+---+---+---+----+------
^
|---char*
Yes, each char*
can point to only a single char at a time. But C++ strings like "ABC"
are stored in memory as a contiguous sequence, without holes and with a 0 char at the end. Therefore, if you have the pointer to 'A', ++pointer
will get you the pointer to 'B'. And you also know that you can do ++
until you find that last '\0'
. (Which is exactly what strlen("ABC")
does - use ++
3 times to find the 0, so it returns 3.)
Char pointers are assumed to point to the beginning of a string.
The pointer itself points to the first character in the string, and code using the pointer assumes that the rest of the string follows it in memory, until it reaches a \0
.
a character pointer does not hold anything except an address.
This address is that of the first element of a char array (or can be at least).
in essence char*
is the same as char[]
A char on the other hand is a value type and cannot hold more than one byte.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With