简体   繁体   English

将结构存储在数组中

[英]Store struct in array

Im am trying to make some code, which mimics a simple malloc-function (in C), though it should only control the memory of a big array, and not the actual physical memory. 我正在尝试编写一些代码,它模仿一个简单的malloc函数(在C语言中),尽管它只控制一个大数组的内存,而不控制实际的物理内存。 To control the "memory", I would like to store segments of META-data in the memory-array. 为了控制“内存”,我想将META数据段存储在内存阵列中。 The META-data is stored as a struct. META数据存储为结构。 My question is, how do I correctly store the struct in the bytes of the array? 我的问题是,如何将结构正确存储在数组的字节中? In the example shown here, I try to store some initial META-data on the starting element of the memory-array; 在此处显示的示例中,我尝试将一些初始的META数据存储在内存阵列的起始元素上。 however I have syntax wrong to do this. 但是我这样做的语法错误。

typedef struct _xMetaData{
    size_t      xSize;
    int*        piNextBlock;
    int     iBlockFree;
}xMetaData;

int8_t memory[ALLOCATE_SIZE];


// Pointer to struct
xMetaData* pxMetaPtr;

xMetaData xInitialData = {BLOCKSIZE, &memory[INITIAL_BLOCK_ADDRESS], BLOCK_FREE};
&memory[0] = xInitialData;

You need to cast the block of memory to xMetaData : 您需要将内存块转换为xMetaData

*(xMetaData *) (&memory[0]) = xInitialData;

You should also be aware of structure padding if you're using a struct for this kind of thing (for example, make sure ALLOCATE_SIZE uses sizeof(xMetaData) and not a hardcoded length, and make sure you always access the memory using the struct.) 如果将结构用于此类事情,则还应该注意结构填充(例如,确保ALLOCATE_SIZE使用sizeof(xMetaData)而不是硬编码长度,并确保始终使用该结构访问内存。 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM