c - 段错误,无法递增

标签 c pointers data-structures segmentation-fault structure

有一个函数询问用户要打开哪个文本文件,打开它,然后将传递到该函数的结构数组以及文件指针传递给另一个函数,该函数将文件中的数据读入该结构。用于测试目的的数组结构仅具有值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/

相关文章:

c - 如何恢复丢失的文件

c++ - 获取内存地址 X 的值

c++ - 使用整数指针操作时如何确定整数数组的结尾?

algorithm - 创建平衡二叉搜索树的时间复杂度?

c - gcc -g 标志 : Moving the Source Code

c - 启动算法时遇到问题

c - 如何处理for循环中的指针

c++ - 从基类指针获取对两个具有不同类型的派生成员变量的访问。

algorithm - 这个搜索算法叫什么?

Mysql B+树实现