Hi, I am practicing sending pointers to functions so wrote the small prog below to swap 2 numbers via pointers sent to a function.
It works fine if I include the dummy "Test" line just before the function call; if I remove that dummy line it crashes after inputting the second value.
I'm completely stumped - can anyone help?
This code creates a pointer, z, with a random value. Whatever happens to be in that memory, So it will be pointing at random memory somewhere. Then, this code attempts to write over that random memory. Could be pointing anywhere. If the pointer is pointing into memory that isn't yours, this will crash.
I would guess that by chance, with your "Test" line in, the random value on the stack that is being used as the value of the pointer is a value that won't cause a crash.
Initialising it with a valid, non-zero value is pointing to a particular variable.
A pointer is nothing more than a single number, and that number is a memory address. When you "point a pointer at a particular variable", what you are really doing is storing the memory address of that variable in the pointer. So:
1 2 3 4
double *z = &myValue;
z = &myValue;
is pointing z at myValue; i.e. it is storing the address of myValue in z.
If you later do:
*z = someOtherValue;
this is not pointing z at another variable; it is changing the value of the variable that z is already pointing to, to be equal to the value of someOtherValue. The result of this will be to change the value of myValue, because that's the variable z is already pointing to.