I have not programmed in C ++ for several years, so I decided to update my memories with pointers.
In the classic example of replacing two numbers, an example
void swapPointersClassic(double *num1, double *num2) { double temp; temp = *num1; *num1 = *num2; *num2 = temp; }
This allows us to call a function call like swapPointersClassic(&foo, &bar); , and since we pass the memory addresses of both variables foo and bar, the function will retrieve the values and perform the exchange. But I began to wonder why I can not do the following?
void swapPointers(double *num1, double *num2) { double *temp; temp = num1; num1 = num2; num2 = temp; }
It seems to me that it makes more sense to me, because we need to create enough temporary storage to store the memory address num1 (instead of a full temporary storage to store the double value * num1). However, it seems that the scope of the function limits the effect of replacing the pointer. After making a call to swapPointers(&foo, &bar); , I see that inside the swapPointers function, foo and bar do indeed swap places. As soon as we exit the swapPointers function, foo and bar are no longer replaced. Can someone help me understand why this is so? This behavior reminds me of a typical cost-based approach, but we are indicating pointers here. So, we can concern only the values indicated by these pointers, but not the pointers themselves?
c ++ pointers swap
Antony
source share