将字符串中的单词提取到动态2D char数组中

问题描述 投票:1回答:1

我有一个包含字符串的动态char数组。我正在尝试从该字符串中提取所有单词到动态2d char数组中。这是我的代码:

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, " ");
}

在我的输出中,input_words_tokenized[j][i]仅包含input_words中的第一个单词或标记。为什么不将其余单词标记化并存储到input_words_tokenized[j][i]中?

c string multidimensional-array tokenize dynamic-arrays
1个回答
0
投票

至少一个问题。

尺寸计算不正确。

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

而不是将大小调整为希望匹配的类型,而是将大小调整为所引用的类型。正确编码,检查和维护更容易。

char **input_words_tokenized = 
    malloc((wordCount(input_words)) * sizeof *input_words_tokenized);
    //                                       ^--------------------^
© www.soinside.com 2019 - 2024. All rights reserved.