为什么我的字符串数组变空 - C

时间:2014-10-13 03:22:09

标签: c arrays

我有这个函数读取文件的内容,该文件具有随机的字母和符号字符串,并且它可以找到文件中出现的单词。它将单词放在数组"单词"。

void scanData(FILE *data_file) {
    const char *words[1000];
    int i;
    size_t wordsI = 0;

    int size = 1;
    char *str;
    int ch;
    size_t length = 0;
    str = realloc(NULL, sizeof(char)*size);
    while((ch=fgetc(data_file)) !=EOF) {
        if(isalpha(ch)) {
            str[length++] = tolower(ch);
            if(length == size) {
                str = realloc(str, sizeof(char)*(size*=2));
            }
        } else {
            str[length++]='\0';
            if(*str!='\0') {
                words[wordsI] = str;
                printf("%s\n",words[wordsI]);
                wordsI++;
            }
            length = 0;
        }
    }
    printf("word %d: %s\n",1, *words);
    } 

问题是在while循环之后,我遍历单词数组,但它只显示空白。我在gdb中调试它,在while循环之后,所有条目都变为空。

1 个答案:

答案 0 :(得分:2)

            words[wordsI] = str;

这会将words[wordsI]设置为str,这意味着如果数据words[wordsI]指向更改,则str指向的数据将发生变化。稍后,您将数据str更改为。你可能想要:

            words[wordsI] = strdup(str);

这将words[wordsI]设置为包含str当前指向的副本的新块或内存。现在,您可以根据需要更改区域str点,而无需更改words[wordsI]中指针指向的内容。

相关问题