vendredi 3 avril 2015

Please help me to check this code for string reverse in C

I'm writing this code to reverse the string, but somehow the last printf() seems can not print out the update string. I want to know why.



#include <stdio.h>

int main() {
char x[] = "abcdefghijklmn";
int j = sizeof(x);
int i = 0;
char t = 'a';
printf("%s,%i\n", x, j / 2);

for (; i < j / 2; i++) {
t = x[i];
x[i] = x[j - i - 1];
x[j - i - 1] = t;
printf("%c,%i,%i\n", x[i], i, j - i - 1);
}

printf("%s\n", x);

return 0;
}


【Update】Thank you guys, after reading all your answers, I've write the code, which is quite clear to show the difference between sizeof() and strlen(), also it was a simpler way to reverse your string. check it and leave your comment if you want.



#include <stdio.h>
#include <string.h>

void StringReverse(char *s) {
int i = 0;
int j = strlen(s) - 1;
printf("sizeof:%i,strlrn:%i\n",sizeof(s),strlen(s));
for (; i < j + 1; i++)
printf("%c", s[j - i]);
}

int main() {
char x[] = "abcdefghijklmn";
printf("sizeof:%i,strlrn:%i\n",sizeof(x),strlen(x));
StringReverse(x);

return 0;
}


The result is :



sizeof:15,strlrn:14
sizeof:4,strlrn:14
nmlkjihgfedcba

Aucun commentaire:

Enregistrer un commentaire