在C中将空指针作为结构数组

时间:2022-09-06 11:19:33

I was trying to use void pointer as Struct array to keep a few struct object together on disk.I want to write records to disk with using void pointer(think as a cluster consist of records).

我试图使用void指针作为Struct数组,以便在磁盘上保留一些结构对象。我想使用void指针将记录写入磁盘(认为是由记录组成的集群)。

void addRecordToDataPage(City record)
{
void* data = malloc(sizeof(City)*RECORD_COUNT);
FILE* fp;
fp=fopen("sampledata2.dat", "rb");
City pageofCity [RECORD_COUNT]; //City is my Struct.
if(!fp) //if it is first access, put the record to pageofCity[0]..
    {
    pageofCity[0]=record;
    data=pageofCity;
    writeDataPageToDisk(data); ..and call the write func.
    return;
    }

fread(&data, sizeof(City)*RECORD_COUNT, 1, fp);
int i=0;
while( (City *)data )
    {
    pageofCity[i] = ((City *)data)[i];
    i++;
    }
pageofCity[i]=record;


}
//and this is my writer function.
void writeDataPageToDisk(void* dataPage)
{
FILE* fp;
fp=fopen("sampledata2.dat", "a");
if(!fp)
    {
    fp=fopen("sampledata2.dat", "wb");
    writeDataPageToDisk(dataPage);
    }
fwrite(dataPage, sizeof(City)*RECORD_COUNT,1,fp);
fclose(fp);
}

in the line of pageofCity[i] = ((City *)data)[i]; I got an memory error. This is my first question in this website, please forgive me about my errors :).

在pageofCity [i] =((City *)data)[i];我收到了内存错误。这是我在本网站的第一个问题,请原谅我的错误:)。

1 个解决方案

#1


0  

There are multiple issues with your code.

您的代码存在多个问题。

The most likely cause for your error looks like:

导致错误的最可能原因如下:

while( (City *)data )

The value of data never changes and you are continuously reading a memory a byte ahead each time in the loop.

数据的值永远不会改变,并且每次循环时,您都在不断地读取一个字节。

if (!fp)
{
    int recordsRead = fread(&data, sizeof(City), READ_COUNT, fp);
    int i=0;
    while( i < recordsRead)
    {
    }
}
pageOfCity[recordsRead] = record;

Also since you are appending one extra element to your array you will need to declare the extra space for that record.

此外,由于您要向阵列追加一个额外元素,因此需要为该记录声明额外空间。

City pageofCity [RECORD_COUNT + 1]; //City is my Struct.

#1


0  

There are multiple issues with your code.

您的代码存在多个问题。

The most likely cause for your error looks like:

导致错误的最可能原因如下:

while( (City *)data )

The value of data never changes and you are continuously reading a memory a byte ahead each time in the loop.

数据的值永远不会改变,并且每次循环时,您都在不断地读取一个字节。

if (!fp)
{
    int recordsRead = fread(&data, sizeof(City), READ_COUNT, fp);
    int i=0;
    while( i < recordsRead)
    {
    }
}
pageOfCity[recordsRead] = record;

Also since you are appending one extra element to your array you will need to declare the extra space for that record.

此外,由于您要向阵列追加一个额外元素,因此需要为该记录声明额外空间。

City pageofCity [RECORD_COUNT + 1]; //City is my Struct.