-
swap function
I'm having trouble with my swap. I'm just trying to compare strings and swap them.
Code:
for(int n=0; n<= 13; n++)
for (int i=0; i<= 13; i++ )
{
int j=i+1;
int result = strcmp( records[i].name, records[j].name);
if ( result > 0 )
swap(i,j);
my problem is that no swap is taking place.
Thanks
-
Well that depends on how you defined swap (which you didn't show us)
-
Code:
. o O ( void swap(int i, int j) { return; } )
-
the values are being swapped, however you are not seeing this beacuse the swap function is being sent copies of the variables.... not the actual variables.
You need to use pointers in order to do this
-
Code:
void alpha(struct employee *records);
...
main()....
....
void alpha(struct employee *records)
{
for(int n=1; n<= 13; n++)
for (int j=1; j<= 13; j++ )
{
int result = strcmp ( records[i].name, records[i+1].name);
if ( result > 0 )
swap (i,j );
i++;
}
}
-
Yes, very good - now paste your swap function (not asking again)
-
Code:
void swap(int *m, int *n);
int main()
{
int x = 3;
int y = 5;
int *ptx;
int *pty;
// Assign addresses of x and y to pointers
ptx = &x;
pty = &y;
swap(ptx,pty);
// could also be called using swap(&x, &y);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
-
Code:
void swap(int &x, int &y)
{
int temp;
temp = x;
x = y;
y = temp;
}
edit: You can ignore my reply, what i posted is a C++ way. Im new too and ive been reading a C++ and C book so i got confused.
-
>what i posted is a C++ way
Don't worry, I did the same thing in the distant past. But Quzah set me straight real quick. :D