Why variable revSentence is still blank? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
14th Apr 2021, 9:17 PM
Mohammad Mehedi Hasan
Mohammad Mehedi Hasan - avatar
4 Answers
+ 4
For one, "revSentence" is initially empty, so accessing non-existing characters via the [] operator is undefined behaviour. It should be noted that the [] operator is only meant for accessing characters in the string, you can't add additional characters with it. Then, you are iterating past the end of the first string in the first loop, which is also undefined behaviour. Since strings are zero-indexed, their length is the first position after the end of the string, and not a valid position itself. Even taking those out of account, using a nested loop is just going to fill "revSentence" with the last character of the original sentence, since the inner loop sets every character to the current character of the original string, which will be the last character during the final iteration. Here is a collection of (in-place) string-reversing techniques if you need it: https://code.sololearn.com/ca110a19a1A2/?ref=app Edit: Seems you changed the code a bit, so the first point no longer applies.
14th Apr 2021, 9:31 PM
Shadow
Shadow - avatar
15th Apr 2021, 3:17 AM
Mohammad Mehedi Hasan
Mohammad Mehedi Hasan - avatar
0
Your character array is uninitialized, adding something to its elements is undefined behaviour. Also, why are you using a nested loop again?
15th Apr 2021, 6:55 AM
Shadow
Shadow - avatar
0
Shadow I'm leaving this code here.. 😂 Thanks Shadow..
15th Apr 2021, 7:05 AM
Mohammad Mehedi Hasan
Mohammad Mehedi Hasan - avatar