As bdb told you, you just got very unlucky, because instead of crashing your program just clobbered
a memory location instead, causing whatever good data that had been stored there to be replaced with garbage
, thus corrupting your data. This corruption can very well give you very unexpected results that you are completely unable to understand how to correct. And when you do this in a larger project, it will be virtually impossible to troubleshoot and correct.
Never use an uninitialized variable, especially not a pointer!
Do you think that pointers are just some magical abstract idea? They are firmly rooted in the silicon lattices of your computer's hardware
! Every single memory location that you store any data in resides in a memory chip. Locations within memory chips, and hence within your computer's memory space, are organized as sequential words, each of which has a unique address -- in most all personal computers, the size of those words is eight bits, a byte. Data larger than one byte uses multiple consecutive bytes. When your program is compiled, every variable is given a memory location whose address is associated with that variable, such that whenever your program accesses a variable's data for either reading or writing, it does so by using the address associated with that variable.
Pointers are simply indirect addressing which you learned in assembly class. Instead of loading a variable with data, you load it with the memory address where that data is located. The key phrase here is: "you load it with the memory address"
. You have to tell your program where that memory location is, which you do by initializing the pointer
. If you don't, then it could just point anywhere and using it will result either in a segfault or in clobbered data.
Why don't you read your own comments?
// *a (sets variable a as a pointer)
// &b (returns the memory address of variable b)
*n = 290;
To implement what the comments say:
int b; // b is a variable; it has a memory location assigned to it
int *a; // a is a pointer; right now, it contains a garbage address and is unusable
a = &b; // a now contains the address of b and is now useable
*a = 290; // now this is a safe operation, since a points to somewhere useable
In police, SWAT, and military training and even just when a civilian spends time on a firing range, one thing that is constantly emphasized is muzzle discipline
know where your firearm is pointing and that it is not pointing towards a friendly. The same applies to using pointers in C: always know where your pointers are pointing. Pointer discipline
is absolutely essential. Otherwise you end up shooting yourself in the foot.