+ 2

Does string placeholder (%s) on C add default characters?

Hey, the program must take a word and output the reverse word, it seems to work, but in some cases the returned word ends with some strange characters, one of those being '@', for example if your input is 'bathroom' or 'mystring'. I don't catch the error here 🤔, thanks in advance. https://code.sololearn.com/cc6zPaR0MBMI/?ref=app

12th May 2021, 4:11 AM
Krys
Krys - avatar
5 Réponses
+ 4
[Continued from previous answer] Also, your line 8 is wrong. Even if I don't consider the null character, 'i-1' should be 'i'. This is because the value of 'i' would be 8 for the input "mystring". As the length of "mystring" is 8, you need a space of i=8, not (i-1)=7 in the string 'w2'. But we also have to consider null character, so the size of 'w2' would be (i+1). Change line 8 to `char w2[i+1];` Then after the for-loop, just before printing the string (that is, on line 12), add the following line `w2[i] = 0;` This will add the null character at the end of the string.
12th May 2021, 5:22 AM
XXX
XXX - avatar
+ 4
Spherk You are not adding the null character ('\0' or 0) before printing the string 'w2'. The null character is very important as printf() (and puts()) stops printing a string when it encounters a null character. Suppose the string is "mystring", it will be represented in memory like this |m|y|s|t|r|i|n|g|0|-|-| ..... Where each |x| represents a memory location with value 'x' in it. As you can see, the first 8 memory locations have your string, then 1 block has null character, and then there are other memory locations which do not belong to your string. printf() will go through your string in memory character-by-character, print each of them, and will stop when it reaches null character. But if there is no null character, it won't stop and will end up printing the values in memory locations which do not belong to your string. These memory locations may have any value.
12th May 2021, 5:13 AM
XXX
XXX - avatar
+ 3
XXX Wao, your answer is super clear, thank you very much! https://code.sololearn.com/chTnnoIUlyyo/?ref=app
12th May 2021, 5:35 AM
Krys
Krys - avatar
+ 2
Mohan 333 This works, but I would like to know why that weird characters were added, also why to let w2 size with 'i' and not with 'i-1' and to change '0' by '\0', since in the other way also worked, thank you!!.
12th May 2021, 4:47 AM
Krys
Krys - avatar
+ 1
Spherk Change your code like this↓↓↓↓ #include <stdio.h> int main() { char w1[100]; scanf("%s", w1); for(int i=0;i<=100; i++){ if(w1[i]=='\0'){ char w2[i]; for(int j=0; j<i; j++){ w2[j]=w1[i-1-j]; printf("%c",w2[j]); } break; } } return 0; }
12th May 2021, 4:27 AM
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜ - avatar