+ 2
Why the commented out statements change the output if uncommented ?
The char array is giving garbage value as output when string function not used but when string function used garbage values don't come .. why it so ? https://code.sololearn.com/c5712a1Nthl1/?ref=app https://code.sololearn.com/cRL53i6b9g8e/?ref=app
9 Réponses
- 1
I'm callin undefined behavior. You can't call for a %s string and then feed it a character array with no null terminator. Weird results. Just code it how it should be coded and you'll have no issues
+ 2
you forgot the null terminating char at the end. You need one extra space for it, but you only left enough for the characters. Look what happens when each array size is increased by one so the null character is taken into account.
https://code.sololearn.com/cPNh67bluhfM/?ref=app
Krishna Kumar comments out and same result when i use my fix. What are you confused about?
https://code.sololearn.com/cSbiaOzykdVL/?ref=app
+ 2
Thanks Martin Taylor and Slick
+ 1
No errors doesn't mean correct! This is C, you're lucky if the compiler tells you. The output is wrong. Look at the "null" code posted above, thats how it should come out
EDIT: and Krishna Kumar look when i leave room for the null char, but then get the strings length, its still 5! null char is not counted
+ 1
Yeah but its only "correct" now cause you took out the other print statements... which wouldve printed garbage. It's still wrong because you print a string without a null terminator. Why not just do this? It don't have to be hard
0
Slice Please uncomment the comments in my code and the output will have no error of null character absence..
Now why does it happen so ?
0
Jokero and Tik still arent printed correctly, this is because the null terminator was left out. It doesnt throw an error and it wont always. But you know that output is wrong
0
Slick I've edited my question so that u understand what I'm asking ..
Please recheck the codes I've posted. In that my output is correct (without any garbage value) when I use string function but it becomes incorrect when I don't use string function.
0
See both the codes I've posted !
One code 'generates the garbage value' after the output but the other code 'doesn't generate the garbage value' after the output.
Why is this difference coming ?