有一个函数询问用户要打开哪个文本文件,打开它,然后将传递到该函数的结构数组以及文件指针传递给另一个函数,该函数将文件中的数据读入该结构。用于测试目的的数组结构仅具有值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;
}
最佳答案
出于某种原因,您正在传递Country**
,然后将其处理为*p[index]
。这是错误的。您可以使用 (*p)[index]
,但正确的方法是首先不要引用 Country*
。
您这样做的方式意味着您有一个指向Country
的指针。当您索引时,您正在移动到下一个指针到指针,这与移动到下一个指针不同。发生未定义的行为。
关于c - 段错误,无法递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32558049/