I have to write a function that will swap the value of two integers around. The definition for the function is swapInts(int *firstInt, int *secondInt);
As it's address' that's being passed in I thought the following would do it:
In fact, I still think that the above should work but I can't figure out why it doesn't. The lines that are calling the above look like this:Code:void swapInts(int *firstInt, int *secondInt)
{
int *tempInt = firstInt;
firstInt = secondInt;
secondInt = tempInt;
}
If I test the value of firstInt and secondInt at the end of the swapInts function they are swapped but when they're output back in the main program they aren't anymore. Why is this?Code:int firstInt = 1;
int secondInt = 2;
swapInts(firstInt, secondInt);
std::cout << "firstInt: " << firstInt << " secondInt: " << secondInt << "\n";
The only way I could get it to work is to use the actual values of the ints like this:
But this seems a bit silly. Surely I could just change the address' that the variables are pointing to?Code:void swapInts(int *firstInt, int *secondInt)
{
int tempInt = *firstInt;
*firstInt = *secondInt;
*secondInt = tempInt;
}