Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

c - C中的结构引发段错误(核心已转储)(Struct in C throwing a segment fault (core dumped))

Sorry in advance since the code isn't entirely in English, not my first language.

(抱歉,代码不是完全用英语写的,不是我的母语。)

Also sorry, my writing is a little bit messy.

(同样抱歉,我的写作有点混乱。)

When trying to pass data from a file to a struct that will store the info from each line of the file, I am met with a Segment Fault (core dumped).

(当尝试将数据从文件传递到将存储文件每一行信息的结构时,遇到段错误(核心已转储)。)

Also the file is structured, so there isn't different input from different lines.

(文件也是结构化的,因此来自不同行的输入没有不同。)

Is there any way I can use memory allocation with a struct?

(有什么办法可以将内存分配与结构一起使用?)

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

typedef struct tipo
{
    int div_1;
    int div_2;
    int div_3;
    int div_4;
    long int cc;
    char nome [60];
    char morada [60];
    int porta;
    char postal [8];
 }  potato;

void read_file (FILE *fp, potato *tipo)
{
    char name[20];
    int w;
    int i;
    printf("Pretende abrir o base.txt?
");
    printf("Se sim, escreva 1.
");


  printf("Caso contrário, escreva 0
");
    scanf(" %d ", &w);
    if(w)
    {
        fp = fopen("base.txt", "r+");
    }
    else
    {
        printf("Indique o nome do ficheiro que pretende abrir: 
");
        scanf(" %s ", name);
        fp = fopen(name, "r+");
    }
    for(i=0;i<EOF;i++)
    {
        getInfo(tipo, fp, i);
    }
        fclose(fp);
}

void getInfo(potato *tipo, FILE *fp, int i) //Auxiliary function
{
    fscanf(fp,"%d.%d.%d.%d",tipo[i].div_1, tipo[i].div_2, tipo[i].div_3, tipo[i].div_4);
    fscanf(fp," %ld ", &tipo[i].cc);
    fgets(tipo[i].nome, 60, fp);
    fgets(tipo[i].morada, 60, fp);
    fscanf(fp," %d ", &tipo[i].porta);
    fgets(tipo[i].postal, 60, fp);
}
  ask by C_Overthinker translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...