gpt4 book ai didi

c - 结构和文件处理

转载 作者:行者123 更新时间:2023-11-30 15:10:58 24 4
gpt4 key购买 nike

我正在编写的程序必须将文本文件中的值存储在各自的变量上。问题似乎出现在内部循环中。我已经定义了各自的结构。程序在外循环中正常运行,但当它在内循环中继续时,文件指针不会从文本文件中读取正确的值并输出“0.0”,并且不会完全继续外循环中的处理。

我的输入文件看起来像这样:

GENERAL
1 4

PANELS
1 2.1 3.1 4.1 5.1 6.1 7.1 1
2 2.2 3.2 4.2 5.2 6.2 7.2 2
1 2.21 3.21 4.21 5.21
2 2.22 3.22 4.22 5.22
3 2.3 3.3 4.3 5.3 6.3 7.3 0
4 2.4 3.4 4.4 5.4 6.4 7.4 4
1 2.41 3.41 4.41 5.41
2 2.42 3.42 4.42 5.42
3 2.43 3.43 4.43 5.43
4 2.44 3.44 4.44 5.44

MATERIAL
1 1000.0 2000.0 3000.0 4000.0
2 1010.0 2020.0 3030.0
3 1010.1 2020.2

CHB
1 10 20 30 2
2 11 22 33 1

这些只是占位符,用于查看它们是否已存储。个位数是整数,而 float 有小数点。

这是代码

typedef struct _open
{
int id;
double length;
double height;
double origX;
double origY;
int frames;

double thickness;
double E;
double v;
}CHBOpening;

typedef struct _panels
{
int id;
double length;
double height;
double origX;
double origY;
double origZ;
double angle;
int nOpenings;
int nReinforcement;
double *xReinf;
double sx;
double xReinf0;

CHBUnit *chb;
CHBOpening *openings[];
}CHBPanel;

typedef struct _chb
{
int nStories;
int nModes;
int nIter;
int nPanels;
CHBPanel *panels[];
}CHBStructure;
int ReadPanelBlock (FILE *fp, CHBStructure *S)
{
int i,j;
S->panels = malloc(S->nPanels*sizeof(CHBStructure));
for (i=0; i< S->nPanels; i++)
{
fscanf(fp,"%d",&S->panels[i].id);
fscanf(fp,"%lf",&S->panels[i].length);
fscanf(fp,"%lf",&S->panels[i].height);
fscanf(fp,"%lf",&S->panels[i].angle);
fscanf(fp,"%lf",&S->panels[i].origX);
fscanf(fp,"%lf",&S->panels[i].origY);
fscanf(fp,"%lf",&S->panels[i].origZ);
fscanf(fp,"%d",&S->panels[i].nOpenings);
if (S->panels[i].nOpenings > 0)
{
S->panels[i].openings = malloc(sizeof(CHBOpening)*S->panels[i].nOpenings);

for (j=0; j<S->panels[i].nOpenings;j++)
{
fscanf(fp,"%d",&S->panels[i].openings[j].id);
fscanf(fp,"%lf",&S->panels[i].openings[j].length);
fscanf(fp,"%lf",&S->panels[i].openings[j].height);
fscanf(fp,"%lf",&S->panels[i].openings[j].origX);
fscanf(fp,"%lf",&S->panels[i].openings[j].origY);
}
}
}
return 1;
}

最佳答案

当您分配pannels时你会的

S->panels = malloc(S->nPanels*sizeof(CHBStructure));

这里的问题是您使用 sizeof(CHBStructure)而不是sizeof(CHBPanel) 。问题在于sizeof(CHBStructure) < sizeof(CHBPanel) ,因此您没有为读取的数据分配足够的内存。

这将导致写入越界和未定义的行为

这是输入文件中“拼写错误”的 补充,这将导致您在没有任何内容可读取时进入内部循环。

关于c - 结构和文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35891376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com