首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么这段C代码会给我一个总线错误?

为什么这段C代码会给我一个总线错误?
EN

Stack Overflow用户
提问于 2012-07-31 02:29:02
回答 6查看 11.8K关注 0票数 3

像往常一样,我在这里阅读了相当多的帖子。我发现了一篇关于总线错误的特别有用的文章,请参见here。我的问题是我不能理解为什么我的特定代码会给我一个错误。

我的代码是试图自学C语言,这是我在学习Java时制作的一个游戏的修改。我在游戏中的目标是获得一个巨大的5049x1文本文件。随机选择一个单词,把它弄乱,然后试着猜出来。我知道该怎么做。无论如何,文本文件的每一行都包含一个单词,如下所示:

代码语言:javascript
运行
复制
   5049
   must
   lean 
   better 
   program 
   now
   ...

所以,我用C语言创建了一个字符串数组,试图读取这个字符串数组并将其放入C中。我没有做其他任何事情。一旦我将文件转换成C语言,剩下的事情就很容易了。更奇怪的是,它遵守了。当我使用./blah命令运行它时,我的问题就出现了。

我得到的错误很简单。上面写着:

代码语言:javascript
运行
复制
zsh: bus error ./blah

我的代码如下。我怀疑这可能与内存或缓冲区溢出有关,但这是完全不科学的,是一种直觉。我的问题很简单,为什么这段C代码会给我这个总线错误消息?

代码语言:javascript
运行
复制
#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 
           }    
        }
    }

}
EN

Stack Overflow用户

发布于 2012-07-31 02:35:01

我怀疑问题出在(fgets(line,256,file))!=NULL)上。读取文件的更好方法是使用fread() (请参阅http://www.cplusplus.com/reference/clibrary/cstdio/fread/)。指定FILE* (C中的文件流)、缓冲区的大小和缓冲区。该例程返回读取的字节数。如果返回值为零,则表示已到达EOF。

代码语言:javascript
运行
复制
char buff [256]; 
fread (file, sizeof(char), 256, buff); 
票数 -1
EN
查看全部 6 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11727383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档