Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is char *A able to hold strings while char A cannot?

Tags:

c++

char

pointers

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.

like image 364
derry30 Avatar asked Nov 06 '13 22:11

derry30


3 Answers

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.)

like image 191
MSalters Avatar answered Oct 12 '22 04:10

MSalters


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.

like image 20
SLaks Avatar answered Oct 12 '22 04:10

SLaks


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.

like image 3
UnholySheep Avatar answered Oct 12 '22 05:10

UnholySheep