简体   繁体   中英

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. I debugged it in gdb and after the while loop, all the entries become empty.

            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. Later, you change the data str points to. 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. Now you can change the region str points to as much as you want without changing what the pointer in words[wordsI] points to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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