[英]Error while trying to create a 2D dynamic array of structs
我必須創建一個二維動態結構數組並從二進制文件中讀取這些結構。 編譯器給我以下錯誤: "error: incompatible types when assigning to type 'S_Apartament {aka struct <anonymous>}' from type 'size_t {aka unsigned int}'"
。嘗試訪問數組的元素時。 代碼:
#include "Header.h"
int main()
{
printf("Hello world!\n");
FILE *f;
f = fopen("Block.bin", "rb");
if(f == NULL)
{
printf("Error opening file");
fclose(f);
exit(1);
}
S_Apartament Flats;
unsigned int floor=0, flats_per_floor=0; // Declaring dimensons of the array
fread(&floor,sizeof(unsigned),1,f);
fread(&flats_per_floor,sizeof(unsigned),1,f);
S_Apartament **ptr = (S_Apartament **)malloc(sizeof(S_Apartament*) * floor);//Declaring an array of pointers
for (int i = 0; i < floor; i++)
{
ptr[i] = (S_Apartament*)malloc(sizeof(S_Apartament)*flats_per_floor);//Each pointer in the array becomes an array of structures.
}
for(int i = 0; i < floor; i++)
{
for(int j = 0; j < flats_per_floor; j++)
{
ptr[i][j]=fread(&Flats,sizeof(S_Apartament),1,f);//Trying to access the array, in order to read from the binary file.
}
}
fclose(f);
return 0;
}
Header 文件:
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
unsigned int Flat_ID;
unsigned int count_Rooms;
unsigned int count_Adults;
unsigned int count_Children;
char Family_Surname[20];
unsigned int day_of_entry;
unsigned int month_of_entry;
unsigned int year_of_entry;
float rent;
int occupancy;
}S_Apartament;
#endif // HEADER_H_INCLUDED
任何幫助,將不勝感激!
您可以嘗試“S_Apartament ptr = (S_Apartament **)malloc(sizeof(S_Apartament ) * floor)”。 sizeof (S_Apartament**) 不是 sizeof (S_Apartament*)。
ptr[i][j]=fread(&Flats,sizeof(S_Apartament),1,f);
fread
返回size_t
類型(讀取或寫入的項目數),但在您的代碼中ptr[i][j]
具有類型: S_Apartament
。
您的程序引發錯誤,因為您嘗試將 integer 值( fread
的返回)分配給S_Apartament
值( ptr[i][j]
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.