【发布时间】:2015-09-14 05:51:46
【问题描述】:
有一个函数询问用户要打开哪个文本文件,打开它,然后将传递给函数的结构数组与文件指针一起传递给另一个函数,该函数将文件中的数据读入结构。用于测试目的的数组结构只有值char name[25];。我可以一次将文件中的一行分配给我想要的相同结构索引,但是当我尝试增加它时,无论我采用什么方法,我都会遇到分段错误。
结构也已定义类型。
代码是:
void oSesame(char usrTxt[], int len, FILE * pFile, Country * p)
{
pFile = fopen(usrTxt, "rw");
if(pFile != NULL)
{
readIn(pFile, &p);
}
else
{
printf("Error opening %s , check your spelling and try again.\n", usrTxt);
}
}
void readIn(FILE * pfile, Country ** p)
{
int count = 0;
int i = 0;
for(i = 0; i<3; i++)
{
fgets((*p[i]).cntName, MAX_COUNTRY_LENGTH, pfile);
}
fclose(pfile);
}
头文件:
//Header.h
#define COUNTRY_MAX 10
#define MAX_COUNTRY_LENGTH 25
#define MAX_CAPITAL_LENGTH 25
typedef struct country
{
char cntName[MAX_COUNTRY_LENGTH];
char capName[MAX_CAPITAL_LENGTH];
double population;
}Country;
int ask(char * usrTxt);
void oSesame(char usrTxt[], int len, FILE * pFile, Country * p);
void readIn(FILE * pFile, Country ** p);
主要代码:
#include <stdio.h> //for testing within main
#include <string.h> //for testing within main
#include "headers.h"
int main()
{
int len;
FILE * fileP;
char UI[25];
Country c[10];
Country * ptr;
ptr = c;
len = ask(UI);
oSesame(UI, len, fileP, ptr);
return 0;
}
【问题讨论】:
-
请发MCVE。
-
你真的为
p[i]->cntName分配了any内存吗? -
我更新了问题,很抱歉给您带来不便,我确实分配了,不是动态分配的,但我希望这不是必需的。
-
0)
rw-->r+, 1)(*p[i]).cntName-->((*p)[i]).cntName
标签: c pointers data-structures segmentation-fault structure