There are no strings in C, but there are pointers to characters.
*pt
is indeed not pointing to a string, but to a single characters (the '1'
).
However, some functions take char*
as argument assume that the byte on the address following the address that their argument points to, is set to 0
if they are not to operate on it.
In your example, if you tried using pt
on a function which expects a "null terminated string" (basically, which expects that it will encounter a byte with a value of 0
when it should stop processing data) you will run into a segmentation fault, as x='1'
gives x
the ascii value of the 1
character, but nothing more, whereas char* pt="123"
gives pt the value of the address of 1
, but also puts into that memory, the bytes containing ascii values of 1
, 2
,3
followed by a byte with a value of 0
(zero).
So the memory (in a 8 bit machine) may look like this:
Address = Content (0x31
is the Ascii code for the character 1 (one))
0xa0 = 0x31
0xa1 = 0x32
0xa2 = 0x33
0xa3 = 0x00
Let's suppose that you in the same machine char* otherString = malloc(4)
,suppose that malloc
returns a value of 0xb0
, which is now the value of otherString
, and we wanted to copy our "pt
" (which would have a value of 0xa0
) into otherString
, the strcpy
call would look like so:
strcpy( otherString, pt );
The same as
strcpy( 0xb0, 0x0a );
strcpy
would then take the value of address 0xa0
and copy it into 0xb0
, it would increment it's pointers to "pt
" to 0xa1
, check if 0xa1
is zero, if it is not zero, it would increment it's pointer to "otherString
" and copy 0xa1
into 0xb1
, and so on, until it's "pt
" pointer is 0xa3
, in this case, it will return as it detected that the end of the "string" has been reached.
This is of cause, not 100% how it goes on, and it could be implemented in many different ways.
Here is one http://fossies.org/dox/glibc-2.18/strcpy_8c_source.html