-
reverse a word
hello all,
please help me to understand the following code; it compile fine but the it gives the correct result only for a word of length =< 3. However if I comment out the statement printf("len = %d\n",len) it works fine for all inputs.
Code:
# include <stdio.h>
# include <string.h>
char *ptr;
int main(int args, char *argv[]){
int len = strlen(argv[1]);
//printf("len = %d\n",len);
int j = len - 1, i;
char ch[len];
for( ptr=argv[1],i=0; i<len; i++,j--){
ch[i]=*(ptr + j);
}
printf(ch);
printf("\n");
system("PAUSE");
}
-
You probably want ch[len+1] and and then put ch[i] = '\0' after the reversing loop.
Of course, ch[len] is non-standard even for C99 compilers, so if you want to follow C standard coding, you'd have to either use a statically sized buffer [remember to check the length before copying], or call malloc to allocate a suitable size string space [don't forget the +1 for the terminating zero].
And
Code:
printf("%s\n", ch);
is probably a better solution, as you would get "interesting" results if the user inputs "d%" or some such [and the right combination of % in the input may even cause a crash]
--
Mats