Here's the key: in assignments,
*pointer = value
means literally "assign the value to the address pointed to by the pointer", but in initializations,
*pointer = address
means "create a pointer and assign the address to it". In assignments, you assign to *pointer, but in initializations, even though you write *pointer, you're assigning to pointer. This isn't how I'd write the C++ standard, but that's how they decided to make it, so you kind of have to deal with it.
In case you're confused about why I keep talking about *pointer as opposed to pointer, here's a brief lesson on pointers:
A pointer is a variable that stores a memory "address", or the number of a byte in the RAM. Obviously, the address isn't very interesting to most people, but what is interesting is the value at that byte. For this we have the dereferencing operator, "*". * means "the value at the address" in English. *message is "the value at the address message".
Pointers were probably my favorite thing to learn as a self-taught programmer, because I always seemed to find that other programmers, in schools, weren't taught the inside works of pointers. Here's a interesting bit of code, see if you can predict its output :) If you don't get it, don't worry about it, it's not really important to what you're doing, but if you do get it, you'll hopefully never have another pointer question again...
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
int main()
{
std::cout << sizeof(short) << ' ' << sizeof(char) << '\n'; // the sizes of short and char, in BYTES
unsigned short *integer = new unsigned short; //letting the OS assign an address to a pointer variable
*integer = 65535; //assigning a number to sizeof(short) consecutive bytes (should be 2 consecutive bytes)
std::cout << (unsigned short)(*((unsigned char*)integer)); //outputting 1 byte of the 2 bytes in *integer as an integer
for (;;);
}
|
Hint: 65535 is 11111111 11111111 in binary (2 bytes full of 1s).