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

问题描述 投票:0回答:1

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

当我在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中停止循环的最佳方法?

c
1个回答
0
投票

你可能想要这个。所有评论都是我的。代码仍然非常差(例如,根本没有错误检查,fopen可能会失败,不必要地使用全局变量,static PERSON p2中的固定大小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;
}
© www.soinside.com 2019 - 2024. All rights reserved.