[英]Void pointer as struct array in C
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
数组来将几个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];
在
pageofCity[i] = ((City *)data)[i];
I got an memory error.我遇到了内存错误。 This is my first question in this website, please forgive me about my errors :).
这是我在这个网站上的第一个问题,请原谅我的错误:)。
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. data
的值永远不会改变,并且每次在循环中都会连续读取内存一个字节。
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.