Problem:
The problem does not stem from the compiler, it's in the code itself, specifically *q = p
, when you dereference the pointer, i.e. use *
, you are accessing the value stored in the pointer which is the address where it points to, in this case the code is invalid because there is no memory assigned to q
, it points to nowhere (at least to nowhere we'd like it to point). You can't store anything in the memory pointed by it because it doesn't exist or is some random memory location given by some garbage value that may be stored in q
.
Behavior explained:
Given the above, and knowing that the value stored in q
can be anything, you can and should expect different results in different compilers, different versions of the same compiler, or even the same compiler in the same machine but in different executions of the same program, at some point it may even be pointing to where you want it to, in a one in a trillion chance, and the program would then give you the expected result, therefore the behavior of your program is undefined.
Fixing it:
As already stated q
needs to be pointing to some valid memory location before you can store a value in that memory location. You can do that by either allocating memory and assigning it to q
or make q
point to an existing valid memory address, e.g.:
int p;
int *q;
q = &p; // now q points to p, i.e. its value is the address of p
Now you can do:
*q = 10; // stores 10 in the memory address pointed by(stored in) q, the address of p
// p is now 10
Or
int value = 20;
*q = value; // stores a copy of value in the address of the variable pointed by q, again p
// p is now 20
Note that if you use extra warning flags like -Wall
or -Wextra
among others, the compiler is likely to warn you about faulty constructs like the one you have.