Reputation: 33
I found this code on the Internet which reverses strings in C using pointers.
I understand the most of it but I don't understand the reverse()
function: why it is using length / 2
?
If I change the condition in second for
loop to length
in reverse()
function, it also displays the same output.
// function to reverse the string s which is an array of some size
void reverse(char *s) {
int length, c;
char *begin = NULL, *end = NULL, temp;
length = string_length(s);
begin = s;
end = s;
for (c = 0; c < length - 1; c++)
end++;
for (c = 0; c < length / 2; c++) {
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
int string_length(char *pointer) {
int c = 0;
while (*(pointer + c) != '\0')
c++;
return c;
}
Upvotes: 0
Views: 129
Reputation: 144780
Let's use a trivial comparison:
The same goes for the letters in the string, if you perform length
swaps, you will get the original string. To get a reversed string, you must stop at half the length of the string.
Note also that the code is more complicated than required. Here is a simplified version:
// function to reverse the string s which is an array of some size
void reverse(char *s) {
char *begin, *end;
for (end = begin = s; *end; end++)
continue;
while (begin < end) {
char temp = *begin;
*begin++ = *--end;
*end = temp;
}
}
Upvotes: 2
Reputation: 49719
Have a look at what is done in the loop:
temp = *end;
*end = *begin;
*begin = temp;
This is some typical swap code that here swaps two characters *begin
and *end
of a string. The pointers iterate from the beginning and the end of the string and approach the middle.
Using the minimal example abcd
, let's see how many characters we have to swap:
abcd (Original string)
dbca (Swapped 'a' and 'd') - iteration 1
dcba (Swapped 'b' and 'c') - finished after 2 iterations
So you only need to swap half of the characters (length / 2
iterations) because you change two of them with each operation. This also explains why you get the original string when changing to length - 1
iterations:
dcba (result from above after 2 iterations)
dbca (Swapped 'c' and 'b') - iteration 3
abcd (Swapped 'd' and 'a') - original string after 4 iterations
Upvotes: 0
Reputation: 31389
Because when c is 0, you will swap the elements at s[0]
and s[length-1]
. When c is 1, you will swap the elements at s[1]
and s[length-2]
and so on. If you used length
instead of length/2
you would reverse the string and then reverse it back to the original.
Upvotes: 0