I'm trying to reverse a string, but it just stays the same. I don't use any modules except <string.h>
and <stdio.h>
.
void rev(s){
char i, temp;
char *sf = s;
char ri = strlen((s) - 1);
char *sl = &s[ri];
for (i = 0; i < ri; i++){
if (*sf != *sl){
temp = *sf++;
s[i] = *sl--; //
s[ri--] = temp; //those two seems to be getting new characters, but it won't
}
else {
ri--;
sf++;
sl--;
}
}
printf("%s", s);
}
The function will not compile at least because the parameter does not have a type specifier.
The type
char
has a little range of acceptable values. So you shall not use it for calculating the length of a string.The call of
strlen
in this declarationinvokes undefined behavior. It seems you mean
that also can invoke undefined behavior for an empty string.
This loop
does not use pointers.
The function can be defined the following way as it is shown in the demonsytrative program below.
The program output is