gpt4 book ai didi

c - 如何用C语言解决这个问题?

转载 作者:行者123 更新时间:2023-11-30 21:05:44 24 4
gpt4 key购买 nike

由于某种原因,函数 loadPerson 始终返回 0 作为输出。

我认为问题与结构体PERSON中的变量score有关,但我不知道问题是什么。例如,我不知道保存函数是否会保存分数或地址的值(因为它是一个指针)。

你能帮我找出问题所在吗?

#include <stdlib.h>
#include <stdio.h>

#define N 3

typedef struct person{
int age;
float *scores;
} PERSON;

int savePerson(PERSON person, char *fileName){
FILE *file;
int result = 0;
file = fopen(fileName,"wb");
if (file){
if(fwrite(&person,sizeof(PERSON),1,file)>0){
result = 1;
}
}
return result;
}

int loadPerson(PERSON *person, char *fileName){
FILE *file;
int result = 0;
file = fopen(fileName,"rb");
if (file){
if(fread(person,sizeof(PERSON),1,file)>0){
result = 1;
}
}
}

int main()
{
char fileName[15] = "file1.bin";
float scores[3] = {2.0,8.0,9.0};
PERSON p1,p2;
int i;

p1.age = 35;
p1.scores = scores;
printf("Salvando\n");
if(savePerson(p1,fileName)){
printf("Saving OK!\n");
}
else{
printf("Saving BAD!\n");
}

if(loadPerson(&p2,fileName)){
printf("Loading OK!");
printf("AGE: %d\n",p2.age);
printf("SCORES:\n");
for(i=0;i<N;i++){
printf("%f,",p2.scores[i]);
}
printf("\n");
}
else{
printf("Loading BAD!");
}
return 0;
}

最佳答案

查看函数原型(prototype):int loadPerson(PERSON *person, char *fileName)您忘记在函数末尾return result;

此外,一旦解决了这个问题,您将在尝试将数组写入文件时遇到问题。您可能希望将结构更新为以下内容:

typedef struct person{
int age;
float scores[N];
} PERSON;

关于c - 如何用C语言解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53103728/

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