Many programmers are confused by the syntax of specifying a pointer.
int* p;
int *p;
int * p;
All of the above declare the same thing: a pointer, p, which either be NULL or the address of an integer-size storage unit in memory.
Thus
int * p = 12;
declares a pointer, p, and assigns it the value 12.
In C and C++ pointers are just variables with special meaning to the compiler such that you are allowed to use special syntax to access the memory location whose value they hold.
Think about this a different way for a moment.
Think of the number "90210". That could be your bank balance. It could be the number of hours since you were born.
Those are all simple "integer" interpretations of the number. If I tell you that it is a Zip Code - suddenly it describes a place. 90210 isn't Beverly Hills in California, it is the [postal] address of Beverly Hills in California.
Likewise, when you write
int * p = 12;
you are saying that "12" is the address of an integer in memory, and you're going to remember that fact in the pointer-variable p
.
You could write
int * p = &12;
This will force the compiler to generate an integer storage unit in the program executable containing the native integer representation of 12, and then it will generate code which loads the address of that integer into the variable p
.
char* p = "hello";
is very different.
12; // evaluates to an integer value of 12
"hello"; // evaluates to an integer value which specifies the location of the characters { 'h', 'e', 'l', 'l', 'o', 0 } in memory, with a pointer cast.
int i = 12; // legal
char h = 'h'; // legal
const char* p = "hello"; // legal
uintptr_t p = "hello"; // legal
The double-quotes in C and C++ have a special meaning, they evaluate to a pointer to the string contained in them, rather than evaluating to the string itself.
This is because
"The quick brown fox jumped over the lazy dog"
wouldn't fit into a CPU register (which are 32 or 64 bits depending on your machine). Instead, the text is written into the executable and the program instead loads the address of it (which will fit into a register). And this is what in C/C++ we call a pointer.