Swap function

Need to swap these....
int *ip = &i, *jp = &j;

Cant get it to work properly. My code:

1
2
3
4
5
6
7
8
void ptswap(int* ip, int* jp)
{
  //int *temp;

  int **temp = ip;
  ip = jp;
  jp = temp;
}


It needs to swap *ip and *jp and not modify i and p which are int variables.
Try this:
1
2
3
4
void ptswap (int *ip, int *jp){
    int *temp = *ip;
    *ip = *jp;
    *jp = *temp;}
Didn't work, throwing me errors for invalid conversion.
You don't want any of the * besides the one after the ints. And I'm assuming you want to swap the pointers, not the data they are pointing to.
Which ones, bc I've tried every combo, and nothing works..
closed account (3hM2Nwbp)
A more copy-and-pasteable version of firedraco's answer.

1
2
3
4
5
6
7
/*Ignore This Code
void swap(int* a, int* b)
{
    int* temp = a;
    a = b;
    b = temp;
}*/


Be sure to review pointers.
Last edited on
Yep, I tried that one, it doesnt output what I need.

Here's my whole program:

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
#include <iostream>
using namespace std;

void ptswap (int *ip, int *jp);

int main() {


int i = 10; 
int j = 20; 
int *ip = &i, *jp = &j; 
 cout << "i = " << i << " j = " << j << endl; // outputs i = 10 j = 20 
 cout << "*ip = " << *ip << " *jp = " << *jp << endl; // outputs *ip = 10 *jp = 20 
ptswap(ip, jp); // this function call swaps the two pointers 
 cout << "i = " << i << " j = " <<j << endl; // outputs i = 10 j = 20 
 cout << "*ip = " << *ip << " *jp = " << *jp << endl; // outputs *ip = 20 *jp = 10

}

void ptswap(int *ip, int *jp)
{;

  int* temp = ip;
  ip = jp;
  jp = temp;
}
closed account (3hM2Nwbp)
What's the output?

*Edit - also, line 21 should give the compiler something to complain about.
Last edited on
i = 10 j = 20
*ip = 10 *jp = 20
i = 20 j = 20
*ip = 20 *jp = 20

where it should be 10 and 20 for the third line and 20 and 10 for the 4thjavascript:editbox1.editPreview()
So you want to swap what the pointers are pointing at then?

1
2
3
int tmp = *i;
*i = *j;
*j = tmp;


Oh, and that stray ; won't actually give any issues, it'll just be a null statement (useless, but not harmful).
Last edited on
closed account (3hM2Nwbp)
Ah obvious oversight, sorry. You'll want to be passing references to the pointers if you want to swap them that way. Alternatively, look at the post above, or use std::swap

1
2
3
4
5
6
void swap(int*& a, int*& b)
{
    int* temp = a;
    a = b;
    b = temp;
}
Last edited on
Yeah that didn't work either, no worries. This was for an assignment, so I was limited
Topic archived. No new replies allowed.