Jump to content

Swap!!! Urgent! Thank you thank you

- - - - -

  • Please log in to reply
2 replies to this topic

#1
fishnewbie

fishnewbie

    Newbie

  • Members
  • Pip
  • 1 posts
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*/



}

#2
fayyazlodhi

fayyazlodhi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 403 posts
I am not sure you understand the concept of swapping correctly.

First your above code is incorrect. i.e. s.a is a integer that you are assigning to a pointer.

The traditional way to swap is to take a temp variable, assign one into temp, copy two into one and finally copy temp into two.

When you try to accomplish above as a separate function and you still want original variables to be changed, then you pass pointers to both the variables to the function which does the same but this time uses pointers.

There is still another method i.e. swapping two variables without using a 3rd. You can easily google that.

Hint: Use bitwise operators
Today is the first day of the rest of my life

#3
AKMafia001

AKMafia001

    Programmer

  • Members
  • PipPipPipPip
  • 119 posts
Oops! I'm wondering how this worked for you, and you are asking for another method than this.

int *aa=s.a;

int *bb=sb;

I'm sure this will give an error like, cannot convert "int" to "int *". This is because you are assigning an integer to a pointer.
And
int *bb=sb; :-) // int *bb=s.b;

Well! I'm sure you didn't tried out the code you provided. A pointer always points to an address of a specific memory location. So your code should look like,

int *aa = &s.a;

int *bb = &s.b;


Also without the pointers,

int aa = s.a;

int bb = s.b;


Hmmmmp! Want to swap it excluding the temporary variable?

Using the actual two variables to swap them out you have to follow the follwing procedure,
  • 1 Assign the sum of both to the first variable.
  • 2 Subtract the second variable from the first and assign it to the second variable.
  • 3 Again subtract the second variable from the first and assign it to the first variable.

This is how you swapped them.

a += b; // a = a + b; Suppose a = 2, b = 3, so a = 5

b = a - b; // b = 2

a = a - b; // a = 3, here a = 3, b = 2


Want to see your code like this? :-)

s.a += s.b;

s.b = s.a - s.b;

s.a = s.a - s.b;


Hope it helped!
I think i'm able to write a code for printing "Hello, World!". Proud of that!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users