int* p;
What the above line means is that p is a pointer to integer
. But since we have not defined what address p holds in itself, ie we have not really defined where exactly p points to. All we know is that the address that it holds (or will hold in future), will actually be the address of an integer. So for now, p is pointing to anything and we can't be sure of it.
Now when you do
*p = 3;
Since at this time, the address in p is not really specified by us, so it is quite possible that p is pointing to an address that can not be written onto. So the behaviour is pretty much undefined.
What you should do is
int myInt;
int* p;
p = &myInt;
*p = 3;
What the above code does is, it makes p hold the address of variable myInt
. And later, write into that address.
What else you can do is that
int* p;
p = (int *)malloc(sizeof(int));
I am not sure if you are familiar with malloc or not (Don't worry, you will be later). But what it does is, it provides p with a chunk of memory ( that is equal to the size of integer ), and now p is pointing to that particular memory block. Now, we don't need to know what exactly was contained in that memory block, but all we need to know is that the memory that has been allocated to us, can be written into without any undefined behaviour.
Cheers