/* * Program to define and demonstrate a function that reversese * a string in place. (Example of working with strings using pointers.) */ #include #include #include void reverse_in_place(char * string); int main(void) { char line[80]; printf("enter a line of text\n"); fgets(line, sizeof line, stdin); /* if input fits into array, fgets stores '\n' character */ char *nl = strchr(line, '\n'); if (nl == NULL) { printf("line too long\n"); return EXIT_FAILURE; } *nl = '\0'; printf("input '%s'\n", line); reverse_in_place(line); printf("reversed '%s'\n", line); return EXIT_SUCCESS; } /* * Reverse a string in place/ * Strategy: Define two pointers that initially point to the * ends of the string. Loop, moving them toward the middle until * they meet, swapping a pair of characters at each step. */ void reverse_in_place(char * string) { char * left = string; char * right = string + strlen(string) - 1; while (left < right) { char tmp = *left; *left = *right; *right= tmp; ++left; --right; /* more compact though less readable char tmp = *left++; *left = *right; *right--= tmp; */ } }