Swapping values using pointers
I have this code fragment
int i = 5;
int k = 7;
int * iPtr;
int * jPtr;
int * kPtr;
iPtr = &i;
kPtr = &k;
I am required to swap i and k using the pointers. This is how I'm doing it:
*jPtr = *kPtr ;
*kPtr = *iPtr ;
*iPtr = *jPtr ;
Is this the best way to do it, or is there a better wa开发者_运维知识库y?
The best way to do that in C++, in my opinion, is with std::iter_swap()
:
#include<algorithm>
// ...
int *iPtr = &i, *kPtr = &k;
std::iter_swap(iPtr, kPtr);
You may think that's an overkill, but I'd disagree if you include <algorithm>
anyway. Of course, in the case of a homework this answer only holds if the instructor's intent is to familiarize you with the STL. If the intent is to introduce you to pointers then the best solution is to introduce a temporary variable, j
:
int j;
int *iPtr = &i, *kPtr = &k, *jPtr = &j;
*jPtr = *kPtr;
*kPtr = *iPtr;
*iPtr = *jPtr;
Just for fun, this will do it without a third variable...
*iPtr ^= *kPtr;
*kPtr ^= *iPtr;
*iPtr ^= *kPtr;
It's an old assembly language trick: XOR swap algorithm
You just forgot to allocate space for the temporary variable:
int i = 5;
int k = 7;
int * iPtr;
int * jPtr = new int;
int * kPtr;
iPtr = &i;
kPtr = &k;
...
*jPtr = *kPtr ;
*kPtr = *iPtr ;
*iPtr = *jPtr ;
delete jPtr;
The reason your teacher told you to use pointer is for you to be familiarized with passing address(pointer) of variables to function. So you can do this sort of thing:
void add_bonus_points(int *x)
{
*x = *x + 100;
}
void main()
{
int a = 2;
printf("%d", a); // 2
add_bonus_points(&a);
printf("%d", a); // 102
}
Regarding swap, here's the code:
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void main()
{
int a = 5;
int b = 7;
swap(&a, &b);
printf("%d %d", a, b);
}
精彩评论