c - 更新函数内的字符串数组

标签 c arrays string malloc c99

我试图将一个带有新字符串的字符串数组传递给一个函数,在这个函数中我想将此字符串添加到数组中并重置该字符串。我似乎无法让它在函数内部工作,但没有它就可以工作

int main(void)
{
    const char* text = "hello world";
    int text_length = strlen(text);

    char* words[text_length];
    char word[text_length];

    int length = 0;
    int k = 0;

    for (int i = 0; i < text_length; ++i) {
        if (isspace(text[i])) {
            words[length] = malloc(strlen(word) + 1);
            strcpy(words[length++], word);
            memset(word, 0, sizeof(word));
            k = 0;
        }

        //...
        //... adding chars to the word
        word[k++]= text[i];
    }
}

这工作得很好,而这则不行:

void add_word(char* words[], char* word, int* words_length, int* word_cursor)
{
    words[*words_length] = malloc(strlen(word) + 1);
    strcpy(words[*words_length++], word);
    memset(word, 0, sizeof(word));
    *word_cursor = 0;
}

int main(void)
{
    const char* text = "hello world";
    int text_length = strlen(text);

    char* words[text_length];
    char word[text_length];

    int length = 0;
    int k = 0;

    for (int i = 0; i < text_length; ++i) {
        if (isspace(text[i])) {
            add_word(words, word, &length, &k);
        }
        //...
        //... adding chars to the word
        word[k++]= text[i];
    }
}

我错过了什么?

最佳答案

我的猜测是它不起作用,因为您没有在word数组中正确添加空终止符。

在第二个示例中,您刚刚复制粘贴了第一个工作代码中的代码,但忘记更改一个关键位:

memset(word, 0, sizeof(word));

在函数add_word中,变量word是一个指针sizeof(word)返回大小指针本身,而不是它指向的内容。

确保 word 中的字符串始终以 null 结尾的最佳解决方案是,当您想要将其视为字符串时,在所需的位置实际显式添加终止符:

if (isspace(text[i])) {
    word[k] = '\0';  // Add null-terminator
    add_word(words, word, &length, &k);
}

关于c - 更新函数内的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58180149/

相关文章:

c - 有没有什么简单的方法可以用C语言创建队列

c - MPI 运行错误 "caused collective abort of all ranks"

php - 合并对象数组中除一个值之外的重复项... php/mysql

c - 如何读取逗号分隔字符串中的名称和整数值?

C 字符串连接使用 memcpy 不追加

c - 为什么这些构造使用增量前和增量后未定义的行为?

c - snprintf 中的 strlen 调用是否导致此段错误?

ruby - 如何删除数组中的空字符串

arrays - mongodb - 将多个文档的数组字段连接到一个数组字段

java - new String() 和普通 String 是如何创建的? java中的字符串类(混淆)