I am in the process of teaching myself C. I have the following code that prints a string char by char forwards and backwards:
#include<stdio.h>
#include<string.h>
main(){
char *str;
fgets(str, 100, stdin);
//printf("%i", strlen(str));
int i;
for(i = 0; i < strlen(str) - 1; i++){
printf("%c", str[i]);
}
for(i = strlen(str); i > -1; i--){
printf("%c", str[i]);
}
}
When run, it gives me the following output (assuming I typed "hello"):
cello
ollec
In addition, if I uncomment the 7th line of code, I get the following output (assuming I typed "hello"):
6 ♠
For the life of me, I cannot figure out what I am doing that is causing the first character in the output to change. In the second example, I know that the string length would be 6 because 'h' + 'e' + 'l' + 'l' + 'o' + '\0' = 6. That is fine, but where is the spade symbol coming from? Why is it only printing one of them?
It is pretty obvious to me that I have some kind of fundamental misunderstanding of what is happening under the hood here and I cant find any examples of this elsewhere. Can anyone explain what is going wrong here?