While I'm here, pointers are a lot easier than many think, but they're often taught using clumsy analogies, which frankly are unhelpful.
A pointer type is a basic type, just like any other (e.g. int, double, char). You create one and it exists somewhere in memory.
int*, char*, double*.... they all take up the same space in memory and essentially they are just a number. Ignore for the moment that they are int pointers or char pointers or double pointers. In memory, they all look the same.
1 2 3 4 5
|
int* p_x; // You have now created a space in memory the size of a pointer.
// It's often the same size as an int. Right now, if you look at that memory that
// effectively is p_x, it'll have some garbage value in it.
p_x = 0 ; // Now, if you look in that piece of memory, it'll have the number 0 in it.
p_x = 3425 ; // Now, if you look in that piece of memory, it'll have the number 3425 in it.
|
Note that in none of the above steps did you actually create a new int; you have not made an int, you have made an int*.
1 2 3 4
|
int y = 12; // Now we HAVE made an int somewhere in memory, with the value 12
// If only we knew its address in memory, we could put that address value in p_x
p_x = &y; // The '&' operator here returns the memory address of y, so now the value of p_x
// is the address of y
|
There is an operation you can carry out on a pointer called "dereferencing". This operation reaches the contents of an address in memory. The address is just a number; the number used for the address is the value of the pointer.
1 2
|
*p_x; // Returns (and in this case doesn't do anything with) the contents of memory address &y
// which in this case we know to be the number 12
|
But wait, you cry. There could be anything in that memory. Anything at all. How does the compiler know how to treat it? Good question. It knows because you explained when you created p_x what kind of things it would point at. We made an int pointer, so the value returned will be treated as an int.
1 2 3 4
|
int z = *p_x; // Z is now whatever value was at memory address &y, interpreted as an int
// So now we've got three objects in memory (two integers, y and z, and an
// int pointer, p_x
// z is 12, y is 12, and p_x is a number that is the address of y in memory
|
If you try something like this:
the compiler should warn that you're trying to assign an integer value to a double; it may carry out some kind of conversion for you, it may just refuse outright, depending on your setup. There are some special values of pointer; if your pointer has a value of 0, it is a null pointer and deliberately does not point anywhere. This is also known as a NULL pointer.
If you understand pointers like this, by actually knowing what they do in terms of the memory, they become an absolute walk in the park. Pointer arithmetic and the relationship between pointers and array follow quite easily if you recall that a pointer is just the number of some other piece of memory somewhere.