I want to make a reverse string function and I have done it like this:
void reverse_str(char s[]) {
int i, j;
char ch;
for(i = 0, j = strlen(s) - 1; i < j; i++, j--) {
ch = s[i];
s[i] = s[j];
s[j] = ch;
}
return ;
}
But for some reason when I change i < j to i != j I get a segmentation fault. This also happens when i and j are pointers. Why?
It’s almost certainly because
iandjpass each other (whether they’re indexes or pointers is irrelevant here). For example, any string with an even number of characters will have this problem.Consider the following sequence for the string
drum:Note that for a string with an odd length, you won’t have this problem since
ieventually equalsj(at the middle character).The
i < jcheck also fixes this problem since it detects both equality of pointers and the pointers passing each other.