像往常一样,我在这里阅读了相当多的帖子。我发现了一篇关于总线错误的特别有用的文章,请参见here。我的问题是我不能理解为什么我的特定代码会给我一个错误。
我的代码是试图自学C语言,这是我在学习Java时制作的一个游戏的修改。我在游戏中的目标是获得一个巨大的5049x1文本文件。随机选择一个单词,把它弄乱,然后试着猜出来。我知道该怎么做。无论如何,文本文件的每一行都包含一个单词,如下所示:
   5049
   must
   lean 
   better 
   program 
   now
   ...所以,我用C语言创建了一个字符串数组,试图读取这个字符串数组并将其放入C中。我没有做其他任何事情。一旦我将文件转换成C语言,剩下的事情就很容易了。更奇怪的是,它遵守了。当我使用./blah命令运行它时,我的问题就出现了。
我得到的错误很简单。上面写着:
zsh: bus error ./blah我的代码如下。我怀疑这可能与内存或缓冲区溢出有关,但这是完全不科学的,是一种直觉。我的问题很简单,为什么这段C代码会给我这个总线错误消息?
#include<stdio.h>
#include<stdlib.h>
//Preprocessed Functions 
void jumblegame();
void readFile(char* [], int);
int main(int argc, char* argv[])
{
    jumblegame();
}
void jumblegame()
{
    //Load File 
        int x = 5049; //Rows
        int y = 256; //Colums
        char* words[x]; 
        readFile(words,x);
    //Define score variables 
        int totalScore = 0;
        int currentScore = 0; 
   //Repeatedly pick a random work, randomly jumble it, and let the user guess what it is
}
void readFile(char* array[5049], int x) 
{
    char line[256]; //This is to to grab each string in the file and put it in a line. 
    FILE *file;
    file = fopen("words.txt","r");
    //Check to make sure file can open 
    if(file == NULL)
    {
        printf("Error: File does not open.");
        exit(1);
    }
    //Otherwise, read file into array  
    else
    {
        while(!feof(file))//The file will loop until end of file
        {
           if((fgets(line,256,file))!= NULL)//If the line isn't empty
           {
               array[x] = fgets(line,256,file);//store string in line x of array 
               x++; //Increment to the next line 
           }    
        }
    }
}发布于 2012-07-31 02:35:01
我怀疑问题出在(fgets(line,256,file))!=NULL)上。读取文件的更好方法是使用fread() (请参阅http://www.cplusplus.com/reference/clibrary/cstdio/fread/)。指定FILE* (C中的文件流)、缓冲区的大小和缓冲区。该例程返回读取的字节数。如果返回值为零,则表示已到达EOF。
char buff [256]; 
fread (file, sizeof(char), 256, buff); https://stackoverflow.com/questions/11727383
复制相似问题