【问题标题】:Segmentation fault, cannot increment分段错误,不能递增
【发布时间】: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]-&gt;cntName分配了any内存吗?
  • 我更新了问题,很抱歉给您带来不便,我确实分配了,不是动态分配的,但我希望这不是必需的。
  • 0) rw --> r+, 1) (*p[i]).cntName --> ((*p)[i]).cntName

标签: c pointers data-structures segmentation-fault structure


【解决方案1】:

您出于某种原因传递了Country**,然后将其作为*p[index] 处理。这是错误的。您可以使用(*p)[index],但正确的方法是首先不要引用Country*

你这样做的方式意味着你有一个指向Country的指针。当您索引时,您正在移动到指向下一个指针的指针,这与移动到下一个指针不同。发生未定义的行为。

【讨论】:

  • 这成功了。有什么建议可以消除流程中的并发症吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 2018-03-30
相关资源
最近更新 更多