【问题标题】:I am completely new to C programming and keep getting a segmentation fault我对 C 编程完全陌生,并且不断遇到分段错误
【发布时间】:2015-03-17 13:16:14
【问题描述】:

这是针对酒店预订系统的,它采用一个 .txt 文件,其中包含 int string string int 行,然后读取该文件并将其放入类型为 room 的数组中......在扫描时它不断给我分段错误.. . 这是上课用的,我不想要一个现成的代码来窃取,但我只是不明白为什么我一直在分段......:/

#include <stdio.h>
#include <stdlib.h>



typedef struct{
    int num; 
    char first[100];
    char last[100]; 
    int type;
    }room;

int main (int argc, char ** argv){

    FILE * myFile;

    if(argc !=2)
        {
                fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
                return EXIT_FAILURE;
        }

        myFile = fopen(argv[1],"r");

        if (myFile==NULL){

            fprintf(stderr, "no open!!\n");
            return EXIT_FAILURE;

        }


        // counter to add elements to my array
        int i = 0;

        char c;
        //array of room with the 150 rooms in it...
        room * rooms = malloc(150 * sizeof(room));

        while ((c = getc(myFile)) != EOF ){

            fscanf(myFile, "%d", rooms[i].num);
            printf("the room num is: %d", rooms[i].num);
            fscanf(myFile, "%s", rooms[i].first);
            fscanf(myFile, "%s", rooms[i].last);
            fscanf(myFile, "%d", rooms[i].type);
            i++;

        }
        fclose(myFile);


}

这是我在我的代码中修复并工作的内容,但它实际上跳过了它从中读取的 .txt 文件中的第一个整数......当它应该是 1 时它只是读取一个零,所以我注意到“ (c = getc(myFile)) != EOF" 是我的问题,它跳过了它应该读取的第一个整数:/

while ((c = getc(myFile)) != EOF ){


            fscanf(myFile, "%d", &rooms[i].num);
            fscanf(myFile, "%s", rooms[i].first);
            fscanf(myFile, "%s", rooms[i].last);
            fscanf(myFile, "%d", &rooms[i].type);

            printf("the room num is: %d and is occupied by %s %s and it is a                                      %d\n", rooms[i].num, rooms[i].first, rooms[i].last, rooms[i].type);
            i++;

        }

.txt 文件的第一行如下: 1 卡里奥斯顿 0

【问题讨论】:

  • 如果你在 linux 上,gdb 是你的朋友。 :-)
  • 我在大学集群上运行,我可以使用 gdp 吗?

标签: c


【解决方案1】:

在您的代码中

fscanf(myFile, "%d", rooms[i].num);

应该是

fscanf(myFile, "%d", &rooms[i].num);

type 相同。

除此之外,您应该始终检查fscanf() 的返回值,以确保正确的scanning。

另外,您需要检查i 的值,以免它访问超出限制的内存。

【讨论】:

  • @user2116459 据我所知,num 不是指针。 :-)
  • @user2116459, rooms 是一个指针(指向room)。 rooms[i]roomrooms[i].numint
  • @user2116459,你需要对rooms[i].type做同样的事情。
  • 看来我在使用 winscp 时遇到了一些问题......我正在使用 sublime,当我保存并检查集群上的文件时,我发现并非所有更改都在应用...... . 我将重写代码并使用您的建议并回复..
猜你喜欢
  • 2015-07-23
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多