gpt4 book ai didi

c - 从函数返回结构体指针(数组)并打印出数据

转载 作者:行者123 更新时间:2023-11-30 16:35:06 24 4
gpt4 key购买 nike

我编写了一段包含人们信息的代码,使用结构将其存储在二进制文件中,然后使用另一个函数将文件中的所有信息写入结构数组,然后将其作为指针返回。

当我在 main 中调用函数并将返回值分配给结构指针时,我尝试使用指针表示法来迭代索引并打印数据。它不会给出任何错误,但会在屏幕上打印垃圾。

代码:

#include <stdio.h>

typedef struct PersonRecords{
char name[20];
int age;
char school[15];
}PERSON;

PERSON p1;

void UpdateRecords();
PERSON* FileToArray();

int main(){
//UpdateRecords();

PERSON* p3;
p3 = FileToArray();
while(p3!=NULL){
printf("%s\t%i\t%s\n\n",(*p3).name,(*p3).age,(*p3).school);
p3+=1;
}
}

void UpdateRecords(){
printf("Enter person name: \n");
fgets(p1.name,sizeof(p1.name),stdin);
printf("Enter person age: \n");
scanf("%f",&p1.age);
fflush(stdin);
printf("Enter person school: \n");
fgets(p1.school,sizeof(p1.school),stdin);

FILE* ptr;
ptr = fopen("PersonRecords.dat","ab");
fclose(ptr);
}

PERSON* FileToArray(){
FILE* pt;
int i = 0;
pt = fopen("PersonRecords.dat","rb");
static PERSON p2[250];
while(fread(&p2[i],sizeof(PERSON),1,pt)!=0){
i++;
}
fclose(pt);
return p2;
}

如何打印从文件中获取的数组中的实际值。我为什么要练习这个?项目中有一部分可以从这样的事情中受益。

编辑:

当没有更多数据时,停止 main 中循环的最佳方法是什么?

最佳答案

你可能想要这个。所有评论都是我的。代码仍然非常糟糕(例如根本没有错误检查,fopen可能会失败,不必要地使用全局变量,固定大小static PERSON p2 in FileToArray而不是动态内存分配等等)

#include <stdio.h>

typedef struct PersonRecords {
char name[20];
int age;
char school[15];
}PERSON;

PERSON p1;

void UpdateRecords();
PERSON* FileToArray(int *nbofentries);

int main() {
UpdateRecords();

PERSON* p3;
int nbofentries;
p3 = FileToArray(&nbofentries); // nbofentries will contain the number of entries read

for (int i = 0; i < nbofentries; i++) {
printf("%s\t%i\t%s\n\n", p3->name, p3->age, p3->school); // instead of (*x).y write x->y
p3 += 1;
}
}


void UpdateRecords() {
printf("Enter person name: \n");
fgets(p1.name, sizeof(p1.name), stdin);
printf("Enter person age: \n");
scanf("%d", &p1.age);
fgetc(stdin); // you need to add this (scanf is quite a special function)
printf("Enter person school: \n");
fgets(p1.school, sizeof(p1.school), stdin);

FILE* ptr;
ptr = fopen("PersonRecords.dat", "ab");
fwrite(&p1, 1, sizeof(p1), ptr); // actually writes something to the file
fclose(ptr);
}

PERSON* FileToArray(int *nbofentries) {
FILE* pt;
int i = 0;
pt = fopen("PersonRecords.dat", "rb");
static PERSON p2[250];
while (fread(&p2[i], sizeof(PERSON), 1, pt) != 0) {
i++;
}
fclose(pt);

*nbofentries = i; // return the number of entries read to the caller
return p2;
}

关于c - 从函数返回结构体指针(数组)并打印出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069237/

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