For example:
const char* f = "123";
As far as I can tell, f
has the address as its value. But why? Shouldn't it generate an error?
For example:
const char* f = "123";
As far as I can tell, f
has the address as its value. But why? Shouldn't it generate an error?
The value of the pointer is not the string, but the memory address of the first character in the string literal.
This is sufficient information, because string literals are null terminated.
What happens is an array of characters of size (number of characters)+1 is created in memory. The value of last character in the array is '\0'
(literally all bits zero), which signals the end of the string literal, so that code that reads that array sequentially knows to not got past that index.
The literal string "123"
is copied from the program file into the process's memory when you execute the program. Usually, literals are placed in a read only memory. That's why the const
required when pointing to string literals. And f
points to the first character of the literal.
const char *f = "123";
// f[0] is '1'
// f[1] is '2'
// f[2] is '3'
// f[3] is '\0'