When I declare a pointer
int *p;
I get an object p
whose values are addresses. No int
s are created anywhere. The thing you need to do is think of p
as being an address rather than being an int
.
At this point, this isn't particularly useful since you have no addresses you could assign to it other than nullptr
. Well, technically that's not true: p
itself has an address which you can get with &p
and store it in an int**
, or even do something horrible like p = reinterpret_cast<int*>(&p);
, but let's ignore that.
To do something with int
s, you need to create one. e.g. if you go on to declare
int x;
you now have an int
object whose values are integers, and we could then assign its address to p
with p = &x;
, and then recover the object from p
via *p
.
Now, C style strings have weird semantics — the weirdest aspect being that C doesn't actually have strings at all: it's always working with arrays of char
.
String literals, like "Hello!"
, are guaranteed to (act1 like they) exist as an array of const char
located at some address, and by C's odd conversion rules, this array automatically converts to a pointer to its first element. Thus,
const char *str = "hello";
stores the address of the h
character in that character array. The declaration
const char str2[6] ="world";
works differently; this (acts1 like it) creates a brand new array, and copies the contents of the string literal "world"
into the new array.
As an aside, there is an obsolete and deprecated feature here for compatibility with legacy programs, but for some misguided reason people still use it in new programs these days so you should be aware of it and that it's 'wrong': you're allowed to break the type system and actually write
char *str = "hello";
This shouldn't work because "hello"
is an array of const char
, but the standard permits this specific usage. You're still not actually allowed to modify the contents of the array, however.
1: By the "as if" rule, the program only has to behave as if things happen as I describe, but if you peeked at the assembly code, the actual way things happen can be very different.