I may be just old and grumpy, but the other answers that I saw seem to be completely missed.
C does not perform array assignments, period. You cannot assign one array to another array with a simple assignment, unlike some other languages (for example, PL / 1, Pascal and many of its descendants - Ada, Modula, Oberon, etc.). In fact, C does not have a string type. It has only character arrays, and you cannot copy arrays of characters (no more than you can copy arrays of any other type) without using a loop or calling a function. [String literals are not really considered a string type.]
Only temporary arrays are copied when the array is embedded in the structure, and you perform the structure assignment.
In my copy of K & R 2nd Edition, Exercise 1-19 requests the function reverse(s) ; in my copy of K & R 1st Edition, it was exercise 1-17 instead of 1-19, but the same question was asked.
Since pointers are not considered at this stage, the solution should use indexes instead of pointers. I believe this leads to:
#include <string.h> void reverse(char s[]) { int i = 0; int j = strlen(s) - 1; while (i < j) { char c = s[i]; s[i++] = s[j]; s[j--] = c; } } #ifdef TEST #include <stdio.h> int main(void) { char buffer[256]; while (fgets(buffer, sizeof(buffer), stdin) != 0) { int len = strlen(buffer); if (len == 0) break; buffer[len-1] = '\0'; /* Zap newline */ printf("In: <<%s>>\n", buffer); reverse(buffer); printf("Out: <<%s>>\n", buffer); } return(0); } #endif /* TEST */
Compile this with -DTEST to enable the test program and not only have the reverse() function.
With the signature of the function asked in the question, you do not call strlen() twice on the input line. Note the use of fgets() - even in test programs, it is a bad idea to use gets() . The disadvantage of fgets() compared to gets() is that fgets() does not delete the ending newline where gets() does. The top of fgets() is that you are not getting an array overflow, and you can determine if the program detected a new line or if it ended with a space (or data) before meeting with a new line.
Jonathan leffler
source share