【发布时间】:2014-06-24 10:51:36
【问题描述】:
我在Linux平台上用libX11和libpthread用C语言设计一个小游戏,所有关卡信息都填充到struct数组Level[Level_Amount]中。
struct Pos
{
int X;
int Y;
};
struct Pos_Info
{
int Flag;
int Drctn;
int Layer;
struct Pos Postn;
int Color;
};
struct In_Out_Chnl
{
struct Pos Drctn[Channel_Amount];
};
struct Check_Point
{
int Remain;
struct Pos Postn[Chk_Pnt_Amount];
};
struct Level_Info
{
char Map[Rbn_Col][Rbn_Row];
struct Pos_Info Draw, Rcvd;
struct Check_Point Chk_Pnt;
struct In_Out_Chnl Channel;
};
struct Level_Info Level[Level_Amount];
我很困惑这是否是从文件中读取和写入结构数组的好方法,如下所示:
FILE *fp;
fwrite(&Level, sizeof(struct Level_Info), Level_Amount, fp);
fread (&Level, sizeof(struct Level_Info), Level_Amount, fp);
结构体(具有不同类型的元素)的内存分配会与编译器或 CPU 不同吗?
有没有更好的方法来安全地保存和读取整个结构?
【问题讨论】:
-
在网上搜索数据序列化
-
是的,可能会有所不同。您应该有自己的方法来一次读取/写入一个字段的结构。这是使用 OO 语言可能会有所帮助的典型情况之一。
-
序列化不是小问题,尝试一些已经实现的解决方案,例如troydhanson.github.io/tpl/index.html
-
@petrbel 谢谢。我访问了该网站,目前 tpl 不支持内部结构上的定长数组后缀。我认为我应该自己从头开始做所有事情。 :-)
-
您的问题不与内存分配有关(例如
malloc),您没有告诉我们什么例如Channel_Amount是。我相信libsdl、JSON -with Jansson library- 和 flexible array members 可能对你有用。
标签: c memory-management struct