Exchange values ​​with pointers

I have this piece of code

int i = 5;
int k = 7;
int * iPtr;
int * jPtr;
int * kPtr;

iPtr = &i;
kPtr = &k;

I need to exchange i and k with pointers. Here is how I do it:

*jPtr = *kPtr ;
*kPtr = *iPtr ;
*iPtr = *jPtr ;

Is this the best way to do this, or is there a better way?

+3
source share
4 answers

best way to do this in C ++, in my opinion, with std::iter_swap():

#include<algorithm>

// ...
int *iPtr = &i, *kPtr = &k;
std::iter_swap(iPtr, kPtr);

You might think that busting, but I would not agree if you turned <algorithm>on anyway. Of course, in the case of homework, this answer is only fulfilled if the instructor intends to introduce you to the STL. If you intend to introduce pointers to you, the best solution would be to introduce a temporary variable j:

int j;
int *iPtr = &i, *kPtr = &k, *jPtr = &j;
*jPtr = *kPtr;
*kPtr = *iPtr;
*iPtr = *jPtr;
+11
source

, ...

*iPtr ^= *kPtr;
*kPtr ^= *iPtr;
*iPtr ^= *kPtr;

: XOR

+6

You just forgot to allocate space for a 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;
+4
source

The reason your teacher told you to use a pointer is that you familiarize yourself with the transmitted address (pointer) of the variables to work with. So you can do things like this:

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

}

As for swap, here is 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);
}
+1
source

Source: https://habr.com/ru/post/1745388/


All Articles