Swap value by pointer

I have a function that takes in
typedef struct{
int a;
int b;
}example
void foo(example s)
{
/* Is is possible to swap without declaring aa and bb pointer like this?
int *aa=s.a;
int *bb=sb;
int *temp;
temp=aa;
aa=bb;
bb=temp*/



}
Last edited on
I think you meant this:

1
2
3
4
5
6
7
8
9
10
void foo(example s)
{
     int *a = &s.a;
     int *b = &s.b;

     int *temp;
     temp = a;
     a = b;
     b = temp;
}


If so, that doesn't swap s.a and s.b for two reasons, (1) you're just swapping the contents of two int pointers. You need to swap what the pointers point to, and (2) s is passed by value so you're just working on a copy. No matter how you swap the two values, you need to pass s by reference. And yes, you can swap without using pointers:

1
2
3
4
5
6
void foo(example& s)
{
     int temp = s.a;
     s.a = s.b;
     s.b = temp;
}
Last edited on
Topic archived. No new replies allowed.