首页 > 解决方案 > 尝试访问函数外部的结构变量后出现分段错误

问题描述

我定义的结构变量如下;

typedef struct
{
    char   basename[33];        /* [C] Name of the 'Base' Node */
        int    Cell_Dimension;      /* [C] Cell Dimension */
    Parameters *BParam;
        int    Physical_Dimension;  /* [C] Physical Dimension */
        int    Number_of_zones;     /* [C] Number of 'Zone' nodes under the 'Base' node */
    int    flagTurbulence;      /* flag to store if its a turbulence problem 0-No / 1-Yes*/
    int    flagTurbModel;       /* flag to Store which turbulence model is to used 1->k-epsilon
                    2->k-omega etc*/
    int    flagConjugateHeat;   /* For conjugate heat transfer*/
    int    flagLES ;        /** LES is ON or OFF*/
    int    flagLESModel;        /** LES is static or dynamic */
    int    SolverScheme;
    LESdatastruct *LESdata;
        int    couplingTag; /* It hold information about the coupling of equations i.e. Coupled solver, semi-Coupled solver and Segregated solver. */
    int     Scheme;    /* It holds the information about Solution Algorithm to be used ie Implicit or semi implicit*/
    int     steadystate; /*It holds the information about if the problem is steady or unsteady...0-> Steady and 1-> Unsteady*/
    int     TimeStepingSchemeTag;
    Zone   *CgnsZone;       /* [C] 'Zone' Nodes under the Base Node */
    int     TotalVar;       //NEW ADDITION///
    int     VARTAG[30];     //NEW ADDITION///
    int     flagCTR;        /** to keep discretly energy conserving scheme ON, available only in LES */ 
    int     restart;
} Base;

/***********************Data Structure for METIS*************************************************************/
typedef struct
{
  idx_t ne;
  idx_t nn;
  idx_t nc;
  idx_t *eptr;
  idx_t *eind;
  idx_t *npart;
  idx_t *epart;
  int ncells;
  int nodes;
  int *elements;
  idx_t objval;
  idx_t nparts;
  idx_t ncommon;
  Base *MetisBase;
} METIS;

我定义了一个名为 NewEleConn() 的函数,其结构如下;

int NewEleConn(Root CgnsRoot,Root Metis,Base *MetisBase){
     MetisBase=(Base*)malloc(1*sizeof(Base));
     MetisBase->Cell_Dimension=10;
return 0;
}

在主要功能中,我做了以下事情;

    int main(){
METIS metisdata;
     ..
    ..
      CgnsRoot = ReadCgnsFile(filename1); 
      Metis=conversion(CgnsRoot);        
      NewEleConn(CgnsRoot,Metis,metisdata.MetisBase);
      printf("%d",metisdata.MetisBase->Cell_Dimension);
    }

在主函数的打印行,即使我在函数内部分配了内存,它也会给我访问结构变量的分段错误错误。

标签: cpointersstructreferenceparameter-passing

解决方案


功能

int NewEleConn(Root CgnsRoot,Root Metis,Base *MetisBase){
     MetisBase=(Base*)malloc(1*sizeof(Base));
     MetisBase->Cell_Dimension=10;
return 0;
}

处理原始指针的副本。函数参数MetisBase是函数的局部变量。函数内变量的任何更改都不会影响原始对象。

您必须通过引用传递指针。例如

int NewEleConn(Root CgnsRoot,Root Metis,Base **MetisBase){
     *MetisBase=(Base*)malloc(1*sizeof(Base));
     ( *MetisBase )->Cell_Dimension=10;
return 0;
}

并像这样调用函数

NewEleConn(CgnsRoot,Metis, &metisdata.MetisBase);

推荐阅读