gpt4 book ai didi

c - 为指针结构赋值会导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:39 25 4
gpt4 key购买 nike

我创建了一个结构和一个该类型的指针。我使用 malloc 为它分配了内存,但是当我尝试实际为其分配一些值时(特别是从文件中读取整数和 float ),它给了我一个段错误,说“在 somelocation 的 ungetwc() 没有可用的源“”。

以下是有关指针和结构的部分代码:

typedef struct {
int *rain;
float *avgtemp;
float *avgwind;
} weather;

weather *year = (weather*) malloc(n*sizeof(weather));
if (year == NULL)
{
return 1;
}

for (i = 0; i!=12; i++)
{
fscanf(infile, "%i %f %f", (year+i)->rain, (year+i)->avgtemp, (year+i)->avgwind);
}

我认为问题可能出在 fscanf 中缺少 & 但当我添加它时,我的 IDE 给了我一个警告,指出 int* 是预期的,但提供了 int** 。

最佳答案

根据您的代码,这是必需的:

typedef struct {
int *rain;
float *avgtemp;
float *avgwind;
} weather;

weather *years = malloc(n * sizeof(weather));
if (year == NULL) {
return 1;
}

weather *year = years;
for (i = 0; i < n; ++i, ++year) {
year->rain = malloc(sizeof(int));
year->avgtemp = malloc(sizeof(float));
year->avgwind = malloc(sizeof(float));
fscanf(infile, "%i %f %f",
year->rain, year->avgtemp, year->avgwind);
}

但是,我真正认为您想要的是struct使用指针:

typedef struct {
int rain;
float avgtemp;
float avgwind;
} weather;

weather *years = malloc(n * sizeof(weather));
if (year == NULL) {
return 1;
}

weather *year = years;
for (i = 0; i < n; ++i, ++year) {
fscanf(infile, "%i %f %f",
&year->rain, &year->avgtemp, &year->avgwind);
}

更新:

yes, I just removed the pointers from the struct, it did solve all the problems I had. Maybe I misunderstood what my professor said.

也许吧。第一种方法(即您的版本)对某些更复杂的用例有效。例如,如果 struct 有一个 char * 字符串,其中字符串长度可以是任意长。

第二个版本更加地道,更易于使用。

否则,在您代码的其他任何地方,当访问一个元素时,我们会做(例如)int rain = *year->rain; 而不是[更简单的] int rain = year->rain;

如果其中一个 struct 成员需要是值的数组(例如)该结构用于年度报告,我们需要(例如)每个月的每月降雨量(相对于当年的累积降雨量),rain [再次] 可能没问题 int *rain ;。但是,鉴于此,由于一年中的月数是固定的,我们可以这样做:int rain[12]; 以保持简单。

关于c - 为指针结构赋值会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53135457/

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