int b = 1; int *a = b;
this is a subtle error. if it works (it should at least throw a warning, but it may depend on compiler flags, I forget, I have not tried to do anything like that in a very long time!) ... anyway if it works it says that a is a pointer that will touch location 1. location 1 is almost certainly not valid memory for your program (most computers, the operating system claims the 'low' order memory areas simply because they are typically allocated first, -- you need memory? 100% of it is available, so I give you location 0..) and if you tried to access it (*a = 42;) it should crash. Modern OS prevent accessing memory that your program is not marked as owning.
pointers and references are very similar. Consider this..
- a variable is a 'name' (eg int x, x is the name) in your code for a block of 1 or more bytes somewhere (eg 4 bytes on the stack for a typical int x).
- a reference can put a new name on a variable. Now you have 2 names that can refer to the same block of bytes.
- a pointer gives you the location of a block of bytes. It can GET to that block and modify it, so it is 'indirectly' a new name for the same data, but you have to 'dereference' it to get there. One way to think of a pointer is that if your computer's memory is a giant array of bytes, a pointer holds the INDEX into that array, just like you can say int i = 3; arr[i] = 11; //i indirectly gets you to a useful location... its not exactly the same, but conceptually, its very close.
- a pointer can refer to a block of bytes that never existed before (the new keyword). A reference MUST refer to an existing thing.