
Originally Posted by
Vithika
In this code, the loop is necessary to iterate through the entire array. The goal is to reverse the elements in the array, which requires looping through the entire array and swapping the elements. A pointer for the start of the array and another for the end of the array would not accomplish this goal since the elements must be swapped in order to reverse the array.
Yeah, you are right. This doesn't work!
Code:
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv) {
char test_str[] = "G4143's test string";
char * bgn_str = test_str;
char * end_str = test_str + strlen(test_str) - 1;
fprintf(stdout, "%s\n", test_str);
while (bgn_str < end_str) {
if (*bgn_str != *end_str) {
char temp = *bgn_str;
*bgn_str = *end_str;
*end_str = temp;
}
++bgn_str;
--end_str;
}
fprintf(stdout, "%s\n", test_str);
return 0;
}