Please help me with string splitting | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Please help me with string splitting

I'm trying to store every single string of a sentence in a array of strings. But somehow my code doesn't work as intended. I've been trying it for 3 hours and still stuck. Please help me https://code.sololearn.com/cUF394PsX064/?ref=app

1st Jun 2021, 10:14 AM
Rishi
Rishi - avatar
4 Answers
+ 3
You forgot to include the <string.h> header for strtok(), the main() function should return an integer, and your control flow for splitting the string was wrong. Here is a corrected version: https://code.sololearn.com/clc3hJ5l059G/?ref=app
1st Jun 2021, 10:44 AM
Shadow
Shadow - avatar
+ 2
If you do it that way around, you access the array out of bounds during the last iteration, where you receive a null pointer and write it into arr[ 4 ] before terminating the loop. That is already undefined behaviour and no longer a valid C program. In this particular case on SoloLearn, "str" seems to be placed directly above "arr" on the stack. Therefore, when you write NULL into arr[ 4 ], you really overwrite the first 8 ( = sizeof( void* ) here ) bytes of "str" with the '\0' character. As a result, the first two pointers in "arr" now point to locations that contain a null terminator, and thus only the newline character is actually printed to the screen at the end.
1st Jun 2021, 11:13 AM
Shadow
Shadow - avatar
+ 1
Shadow yes I got it. Thank you thank you thank you thank you thank you!☺️😊
1st Jun 2021, 11:19 AM
Rishi
Rishi - avatar
0
Shadow I feel like both I understood and not. I made a little remodeling in your code and suddenly it's not working https://code.sololearn.com/cwvqwx34JUny/?ref=app
1st Jun 2021, 10:53 AM
Rishi
Rishi - avatar