简体   繁体   English

C从文本文件中读取单词

[英]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. 我正在编写一个简单的函数,将已经打开的3个文件作为输入3,然后扫描文件中的每个字符,填充一个char数组,直到到达''空格或找到换行符为止。 However, my method of filling an array keeps giving me a Segmentation fault and I'm not really sure why. 但是,我填充数组的方法一直给我一个Segmentation fault ,我不确定为什么。 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. 现在,我只是试图打印来控制台word []数组中填充的单词,然后使用memset清除下一个单词。

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. 您的word数组是指针数组,而不是字符数组。
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; 正如您所声明的,变量“ word”不是char数组/ cstring,而是指向大小为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. 这将起作用,但是您尚未使用“ malloc”初始化字符串,因此在尝试更改未分配给程序的部分内存时出现“ Segmentation Fault”错误。

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. 因为它们在创建时指向内存的随机部分,所以代码可能不会总是给您“ Segmentation Fault”错误,因为它可能指向分配给程序的部分内存。 Worst case, you will have a really hard-to-track bug. 最坏的情况是,您将遇到一个很难跟踪的错误。

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

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