Johnny Sack
Johnny Sack

Reputation: 29

Extracting words from a string into dynamic 2D char array

I have a dynamic char array that contains a string. I'm trying to extract all the words from this string into a dynamic 2d char array. Here's my code:

int rows = 1;
char *input_words = malloc((rows)*sizeof(char)); 
input_words = lowerCase(getInputWords(MAX_LINE_LEN, input_file)); //retrieves a string of words
char **input_words_tokenized = malloc((wordCount(input_words))*sizeof(char)); 

for(i = 0; i < wordCount(input_words); i++) {
    input_words_tokenized[i] = malloc(MAX_KEY_LEN*sizeof(char)); 
}


char *t = strtok(input_words, " ");
j = 0;
while(t) {
    for(i = 0; i < strlen(t); i++) {
        strcpy(&input_words_tokenized[j][i], &t[i]);
        printf("%c", input_words_tokenized[j][i]);
    }
    j++;

    t = strtok(NULL, " ");
}

In my output, input_words_tokenized[j][i] only contains the first word or token from input_words. Why aren't the remaining words being tokenized and stored into input_words_tokenized[j][i]?

Upvotes: 2

Views: 53

Answers (1)

chux
chux

Reputation: 154235

At least one issue.

Incorrect size calculation.

char **input_words_tokenized = 
    malloc((wordCount(input_words))*sizeof(char));
    // wrong type                          ^--^

Instead of sizing to the hopefully matching type, size to the referenced type. It is easier to code right, review and maintain.

char **input_words_tokenized = 
    malloc((wordCount(input_words)) * sizeof *input_words_tokenized);
    //                                       ^--------------------^

Upvotes: 1

Related Questions