c - 尝试访问函数外部的结构变量后出现分段错误
问题描述
我定义的结构变量如下;
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);
}
在主函数的打印行,即使我在函数内部分配了内存,它也会给我访问结构变量的分段错误错误。
解决方案
功能
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);
推荐阅读
- database-administration - ArangoDB 按需压缩文件空间回收的最佳实践
- javascript - 不变违规:元素类型无效:期望字符串或类/函数,但得到:对象。检查渲染方法
- python - 多步预测 LSTM 模型
- java - 在 DropWizard 中禁用 Swagger Bundle
- sql - 在满足条件之前如何获取最新数据?[SQL]
- c# - 如何设置默认值而不是从 Create-View 的下拉列表中选择
- apache-spark - 为什么在 PySpark 中使用 UDF 而不是 Function?
- c# - 我怎样才能拥有一个包含两个 .Net Core 项目的解决方案并使用两个 Startup.cs 文件来设置服务?
- visual-studio - LLVM 7.0 在 Visual Studio 2015 上不提供特定的平台工具集
- spring - JPA - 使用 @OrderBy 注释的列表不排序项目