Why would my programme work only if I put in a "dummy line"?

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?
Many thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

int main ()

{
    void swapTwoValues (double *, double *);
    double a, b;
    double * pa = &a, * pb = &b;
    std::cout << "Let's swap 2 values" << std::endl;
    std::cout << "Input floating point number 1 : ";
    std::cin >> a;
    std::cout << "Input floating point number 2 : ";
    std::cin >> b;

    std::cout << "Test" << std::endl;// This is the "dummy line"

    swapTwoValues (pa, pb);
    std::cout << "These are now swapped to " << a << " " << b << std::endl;
    return 0;
}
void swapTwoValues (double * x, double * y)
{
    double *z;
    *z = *x;
    *x = *y;
    *y = *z;
}
1
2
 double *z;
    *z = *x;


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.

The bug is in this code, in swapTwoValues.
Ah! Sois the lesson that when I declare a pointer I should initialise it at the same time as pointing to a particular variable?
Many thanks for this.
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 myValue;
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.
Many thanks to both of you for this help: lesson learnt!
You're welcome - hope it helped!
Topic archived. No new replies allowed.