I am following Kernighan and Ritchie to learn C and my solution to exercise 1.19, to reverse a string, does not work. Intermediate print out indicates it is working, but the string is not reversed. Please help, and thanks.
#include <stdio.h>
#define MAXLINE 1000 // max allowed line length
int getline(char line[], int max);
void reverse(char line[], int len);
/* reverse the characters in a line of input */
main() {
int len; // current line length
char line[MAXLINE]; // current line
while((len = getline(line, MAXLINE)) > 0) {
printf("before:***%s***\n", line);
reverse(line, len);
printf("after:***%s***\n", line);
}
return 0;
}
int getline(char s[], int lim) {
int c, i;
for(i = 0;i < lim - 1 && (c = getchar()) != EOF && c != '\n';++i)
s[i] = c;
s[i] = '\0';
return i;
}
void reverse(char line[], int len) {
int i, m = 0, x = 0;
char c;
printf("reverse before:\n");
for(x = 0;x < len;x++)
printf("%d ", line[x]);
printf("\n");
for(i = len - 1;i >= 0;i--, m++) {
c = line[m];
printf("i: %d\n", i);
printf("c: %d\n", c);
printf("line[m] BEFORE: %d\n", line[m]);
printf("line[i] BEFORE: %d\n", line[i]);
line[m] = line[i];
line[i] = c;
printf("line[m] AFTER: %d\n", line[m]);
printf("line[i] AFTER: %d\n", line[i]);
}
printf("reverse after:\n");
for(x = 0;x < len;x++)
printf("%d ", line[x]);
printf("\n");
}