I want to know what’s wrong with my code.
It’s supposed to exchange the two word specified by the user,
but it does nothing. A little help would be nice.
#include <stdio.h>
void changeW(char *ptab1, char *ptab2){
char tmp;
tmp = *ptab1;
*ptab1 = *ptab2;
*ptab2 = tmp;
printf("%s %s",ptab1,ptab2);
return;
}
int main(void) {
char tab1[25];
char tab2[25];
printf("type two words");
scanf("%s %s",tab1,tab2);
changeW(tab1,tab2);
return 0;
}
corrected code, but still a problem ! i can swap small words but when they get long, i got weird characters in the terminal such as �����.
void changeW(char *ptab1, char *ptab2){
int l;
if(length(ptab1)<length(ptab2)){
l = length(ptab2);
}
else {l=length(ptab1);}
for(int i=0; i<l;i++){
char tmp;
tmp =ptab1[i];
ptab1[i] =ptab2[i];
ptab2[i]=tmp;
}
printf("%s %s",ptab1,ptab2);
return;
}
int main(void) {
char tab1[25];
char tab2[25];
printf("type two words");
scanf("%s %s",tab1,tab2);
changeW(tab1,tab2);
return 0;
}
Ok i found the solution thanks all for your help.
All you got to do is, in changeW,
printf("%s\t%s",ptab1,ptab2);
the single space seems not enough to separate both words, a tab is fine.
Last edit :
in fact, searching for the longest table is useless, as tab1 and tab2 are both 25 character long.
for(int i=0; i<25;i++)
works fine.
To exchange the two words without a temporary buffer variable you’ll need to do some bit tricks.
The
^operator is the bitwise XOR boolean operation.The trick that makes this work is that
(a^b) ^ a=bandb^(a^b)=afor anyaandb. The swapping part is thus: