简体   繁体   中英

C Reading words from text file

I'm writing a simple function that takes as input 3 already opened FILES's, then scans through each character in the file, filling up a char array until a ' ' whitespace is reached or a newline is found. However, my method of filling an array keeps giving me a Segmentation fault and I'm not really sure why. For now I am just attempting to print to console the words that were filled in the word[] array, then clearing it with memset for the next word.

hash_table_t training(FILE *D1, FILE *D2, FILE *D3, int size)
{

char *word[200];
char c;
int i = 0;

while ((c = fgetc(D1)) != EOF)
{
    while (((c>='a') && (c<='z')) || ((c>='A') && (c<='Z')))
    {
        //add to char array
        *word[i++] = c;
    }
    if(c == ' ' || c=='\n')
    {
        //hash word (print chars for now)
        for (i=0; *word[i] != ' '; i++)
        {
            printf("%c", *word[i]);
        }

    }
    memset (word, ' ', 20);

}

fclose(D1);
fclose(D2);
fclose(D3);
}

Your word array is a array of pointer, not a array of character.
You should change

char* word[200];

to

char word[200];

and

*word[i];

to

word[i];

您将word声明为字符指针数组,为它们分配字符 ,然后尝试取消引用这些值。

The variable "word" as you have declared it is not a char array/cstring, but it is a pointer to a string with a size of 200; this would work but you have not initialized the string with "malloc" hence the "Segmentation Fault" error as you are trying to change a part of memory not allocated to your program.

Edit: Also, as a tip, always initialize pointers as soon as creation; because they are pointing to random parts of memory upon creation, the code may not always give you a "Segmentation Fault" error, because it may point to a part of memory that IS allocated to your program. Worst case, you will have a really hard-to-track bug.

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