1

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?

SU3
  • 5,064
  • 3
  • 35
  • 66
dan gha
  • 79
  • 4
  • Even string literals have a memory address. – Mikel F Feb 07 '17 at 22:43
  • 1
    See this answer: http://stackoverflow.com/a/9633233/1865694 – Alex Zywicki Feb 07 '17 at 22:43
  • 1
    It is not a string. It is a temporary array of chars. – Sam Mokari Feb 07 '17 at 22:43
  • 1
    String literals like this will be placed in the read only data segment of the executable file and will not occupy space on the applications stack or heap. Thats why c++ wants you to make it `const`. – Paul Rooney Feb 07 '17 at 22:46
  • @SamMokari There is nothing temporary about it. – Yakk - Adam Nevraumont Feb 07 '17 at 22:52
  • 1
    You stated "as far as I can tell", I am guessing that you may be looking at "f" in a debugger. Most debuggers interpret char* as a special kind of "type", i.e. a "string". If f was an int*, your debugger WOULD have shown you f's value as an address and would NOT have done any "dereferencing", but since it is a char*, the debugger probably showed you its dereferenced, nul char terminated character array in ASCII (although a good debugger would have ALSO shown the char * address value in f). – franji1 Feb 07 '17 at 23:01

2 Answers2

3

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.

SU3
  • 5,064
  • 3
  • 35
  • 66
  • The language specifies that. That's the meaning of `"123"`. – SU3 Feb 07 '17 at 22:55
  • How does the compiler know what I meant? by the same logic int* f=2 should mean that f is the address where 2 is saved, but it doesn't. – dan gha Feb 07 '17 at 23:00
  • 1
    No, that's not the same logic. `2` and `"2"` are two different things. You can think of string literals as a special case. The type of `"123"` is `const char [4]`. That's an array of `char` of size 4. You can assign that to a pointer, because array types decay to pointers to the first element. – SU3 Feb 07 '17 at 23:06
1

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'