我有以下四种结构在我的计划阅读结构对象无效*指针
struct SType{
int type;//struct type
};
struct S1{
};
struct S2{
};
struct S3{
};
我使用下面的代码保存这些结构的状态在一个文件中:
空隙存储(S型结构S1,空隙* S){
//open file and stuff //s points to either one of the last three structs fwrite(&s1,sizeof(s1),1,file); fwrite(s, size, 1, file); //structs are always saved in the file in pairs of SType and either one of the last three structs }
现在当我试图从文件中使用下面的代码检索对的第二个结构时,我得到分段错误。那么,如何使用fread()来检索任意结构类型的对象呢?
void read(){
void *record;
//read struct SType object from the file
//now read the second struct of the pair
fread(record,size,1,file);
}
我们需要更多的代码。我*猜测*是你没有分配内存来读取'struct'。尽量减少你的代码以免“垃圾”给每个人,但是一个错误代码的小实例将是完美的(而不是伪代码) – noelicus
@noelicus我想读取结构或者将其引用为void *指针....当我读结构时,结构对象read可以是s1,s2或s3的一种类型....稍后在我的代码中,我将把void *指针转换为适当的结构类型指针。 – thunderbird
我的观点是你已经将'read' *写入有效的记忆*,并且我猜测你可能没有那样做。我不得不猜测,因为你没有包括代码,这是我的另一点! – noelicus