c - unexpected results on simple string reverse algorithm -
i'm relatively new c. wanted lern language bit solving coderbyte challenges.
but i'm stucked @ first. supposed simple string reverse algorithm.
when input things "asdf" or "1234567" output correct ("fdsa", "7654321"). when type "12345678" or "thisiscool" "87654321▒@"/"loocsisiht@" result. don't know @ comming from.
this code:
#include <stdio.h> #include <string.h> void firstreverse(char str[]) { int len = strlen(str); char nstr[len]; int i; for(i = 0; < len; i++) { nstr[i] = *(str+len-1-i); } printf("%s\n", nstr); } int main(void) { char str[100]; firstreverse(gets(str)); return 0; }
can please tell me can find error? in advance :)
as other answers have mentioned, you're missing terminator. should noted it's bad practice allocate strings way did. array should have fixed size if create way.
you should instead do:
char * nstr = malloc(sizeof(char) * (len+1));
thereby allocating size of each character (1 byte) times lenght. note +1 because need room string terminator.
when call printf(, string); , it's gonna start first letter , print terminator. since have no terminator here, prints random characters, such @.
what you're gonna wanna fix that, adding:
nstr[i] = '\0';
after loop.
also remember free allocated memory.
Comments
Post a Comment