If you declare a variable of some type, then you can also declare another variable pointing to it.
For example:
int a;
int* b = &a;
So in essence, for each basic type, we also have a corresponding pointer type.
For example: short
and short*
.
There are two ways to "look at" variable b
(that's what probably confuses most beginners):
You can consider b
as a variable of type int*
.
You can consider *b
as a variable of type int
.
Hence, some people would declare int* b
, whereas others would declare int *b
.
But the fact of the matter is that these two declarations are identical (the spaces are meaningless).
You can use either b
as a pointer to an integer value, or *b
as the actual pointed integer value.
You can get (read) the pointed value: int c = *b
.
And you can set (write) the pointed value: *b = 5
.
A pointer can point to any memory address, and not only to the address of some variable that you have previously declared. However, you must be careful when using pointers in order to get or set the value located at the pointed memory address.
For example:
int* a = (int*)0x8000000;
Here, we have variable a
pointing to memory address 0x8000000.
If this memory address is not mapped within the memory space of your program, then any read or write operation using *a
will most likely cause your program to crash, due to a memory access violation.
You can safely change the value of a
, but you should be very careful changing the value of *a
.