Click here to Skip to main content
14,977,259 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
‘a tailor has become a sailor after he has experienced a voyage with his captain friend’. In the above given sentence how to store the words in a two dimensional array like
array = {"a", "tailor", "has", "become", "a", "sailor", "after", "he", "has", "experienced", "a", "voyage", "with", "his", "captain", "friend"}

My code is:
#include <stdio.h>
#include <string.h>

int main()
    char line[1000];
    scanf("%[^\n]", line);
    int l=strlen(line),i,count=0;
        if(line[i]==' '){
    char arr_word[count+1][26];
    int j,ind=0;
            if(line[ind]==' '){
    return 0;

What I have tried:

I have tried the above given code but it stores some garbage value at the end of each word. Please help me.
Updated 26-Feb-21 21:36pm
Rick York 27-Feb-21 2:59am
Your logic was cut off.

1 solution

The reason you see garbage is because you are not storing the terminating null character of the strings. You always need to store one more character than string's length to account for that null character.

Why are you using the literal value 26? That should a macro definition, or a constant value in C++. Literal values should be avoided, especially when they are used in multiple places.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900