试图创建一个二维动态结构阵列时出错。

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

我必须创建一个二维动态结构数组,并从一个二进制文件中读取这些结构。编译器给我以下错误。"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;
}

头文件。

#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

希望能得到帮助

c arrays structure dynamic-memory-allocation
1个回答
0
投票
ptr[i][j]=fread(&Flats,sizeof(S_Apartament),1,f);

fread 返回 size_t 类型(读取或写入的项目数),但在您的代码中 ptr[i][j] 具有类型。S_Apartament.

你的程序引发了错误,因为你试图分配一个整数值(返回的是 fread)到一个 S_Apartament 值 (ptr[i][j])


0
投票

你可以试试 "S_Apartament"。ptr = (S_Apartament **)malloc(sizeof(S_Apartament))。) * sizeof (S_Apartament**)不是 sizeof (S_Apartament*)。

© www.soinside.com 2019 - 2024. All rights reserved.