[英]Returning a structure pointer(array) from a a function and printing out the data
我編寫了一段可以提供信息的代碼,使用結構將其存儲在二進制文件中,然后使用另一個函數將文件中的所有信息寫入結構數組,然后將其作為指針返回。
當我在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;
}
我如何在文件中獲取數組中的實際值。 我為什么要練習這個? 項目中有一部分可以從類似的東西中受益。
編輯:
當沒有更多數據時,停止主循環的最佳方法是什么?
您可能想要這個。 所有評論都是我的。 代碼仍然極差(例如,根本沒有錯誤檢查, fopen
可能失敗,不必要使用全局變量, FileToArray
固定大小的static PERSON p2
而不是動態內存分配等)。
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.