Reputation: 21
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.
Upvotes: 0
Views: 129
Reputation: 18960
void changeW(char *ptab1, char *ptab2)
{
size_t l1 = strlen(ptab1), l2 = strlen(ptab2);
size_t l = l1 > l2 ? l1 : l2;
size_t i;
for (i = 0; i <= l; i++) {
char tmp = ptab1[i];
ptab1[i] = ptab2[i];
ptab2[i] = tmp;
}
}
To exchange the two words without a temporary buffer variable you’ll need to do some bit tricks.
void changeW(char *ptab1, char *ptab2)
{
size_t l1 = strlen(ptab1), l2 = strlen(ptab2);
size_t l = l1 > l2 ? l1 : l2;
size_t i;
for (i = 0; i <= l; i++) {
ptab1[i] ^= ptab2[i];
ptab2[i] ^= ptab1[i];
ptab1[i] ^= ptab2[i];
}
}
The ^
operator is the bitwise XOR boolean operation.
0^0=0
0^1=1
1^0=1
1^1=0
The trick that makes this work is that (a^b) ^ a=b
and b^(a^b)=a
for any a
and b
. The swapping part is thus:
new_p2 = p2 ^ (p1 ^ p2) = p1
new_p1 = (p1 ^ p2) ^ new_p2 = (p1 ^ p2) ^ p1 = p2
Upvotes: 0
Reputation: 23699
You are just switching the two first characters. To swap strings, you have to use loops.
#include <stdlib.h>
#include <string.h>
void changeW(char *p1, char *p2, size_t p1_len)
{
char *tmp = malloc (p1_len); /* or [C99] char tmp[p1_len]; */
strcpy (tmp, p1);
strcpy (p1, p2);
strcpy (p2, tmp);
}
Another possibility is to swap pointers.
#include <stdio.h>
#include <stdlib.h>
void swap_strings(char **p1, char **p2)
{
char *tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
int main (void)
{
char s1[] = "hello";
char s2[] = "word";
char *p1 = s1;
char *p2 = s2;
puts(p1);
puts(p2);
swap_strings(&p1, &p2);
puts(p1);
puts(p2);
return 0;
}
Upvotes: 1