简体   繁体   English

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

[英]Why does my string array become empty - C

I have this function that reads the content of a file, which has random strings of letters and symbols, and it finds words that occur in the file. 我具有读取文件内容的功能,该文件包含字母和符号的随机字符串,并查找文件中出现的单词。 It puts the words in the array "words". 它将单词放入“单词”数组中。

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

The problem is that after the while loop, I traverse the words array but it just shows blank. 问题是,在while循环之后,我遍历了单词array,但它只显示为空白。 I debugged it in gdb and after the while loop, all the entries become empty. 我在gdb中调试了它,而while循环之后,所有条目都变为空。

            words[wordsI] = str;

This sets words[wordsI] equal to str which means that the data words[wordsI] points to will change if the data str points to changes. 这将words[wordsI]等于str ,这意味着如果数据str指向更改,则数据words[wordsI]指向将更改。 Later, you change the data str points to. 以后,将数据str点更改为。 You probably want: 您可能想要:

            words[wordsI] = strdup(str);

This sets words[wordsI] to a new chunk or memory containing a copy of what str currently points to. words[wordsI]为一个新的块或内存,其中包含str当前指向的副本。 Now you can change the region str points to as much as you want without changing what the pointer in words[wordsI] points to. 现在,您可以将区域str点更改为任意数量,而无需更改words[wordsI]的指针指向的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM