Your code seems to mix the concepts of using an index (like 0
or strlen(s)-1
) or using pointers. Even in a comment you wrote "swap the characters s[i]
and s[j]
" but you declared i
and j
as char*
variables.
The second mistake is that you swap the pointer values, not the characters where the pointers point to.
You should decide if you want to use pointers or index to access the characters.
Solution using pointers:
void stringReverse(char* s){
//in order to swap the characters s[i] and s[j] make a temp
char temp;
char* i = s;
/* according to the standard, the behavior is undefined if the result
* would be one before the first array element, so we cannot rely on
* char* j = s + strlen(s) - 1;
* to work correct. */
char* j = s + strlen(s);
if(j > i) j--; // subtract only if defined by the C standard.
while(i < j){
temp = *i;
*i = *j;
*j = temp;
i++;
j--;
}
//end of the while loop means that it reversed everything (no need for if/else)
}
Solution using index:
void stringReverse(char* s){
size_t i = 0;
size_t j = strlen(s)-1;
//in order to swap the characters s[i] and s[j] make a temp
char temp;
while(i < j){
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
//end of the while loop means that it reversed everything (no need for if/else)
}
The compiler should warn about some of the problems in the original source code if enough warnings are enabled. I suggest to always enable as many warnings as possible.