将结构体信息放入一个大数组中

Putting Struct information into one big array

本文关键字:一个 数组 信息 结构体      更新时间:2023-10-16

我正在寻找一种将整个结构信息放入数组的方法。这样做的原因是我正在使用的函数需要从中读取一系列信息。与其调用这个函数 X 次,其中 X 是我在结构中的字段数,我想将整个 blob 信息放入一个数组中并将其发送出去写入。

这就是我在想的:

typedef struct
{
    short powerLevel[100];
    short unitInfo[4];
    short unitSN[6];
} MyDeviceData;
int main()
{ 
    MyDeviceData *devicePtr;
    MyDevieData deviceObject;
    short structInfo[sizeof(MyDeviceData) / sizeof(short)];
    //put all of MyDeviceData arrays into single array structInfo
    ????????
    //call function with new array that has all the structs information
   /* do stuff */

这至少是在正确的方向上吗?

编辑!!:好的,我确定了以下解决方案,以防其他人将来遇到这个问题。希望它不会太糟糕:

//memcpy struct values into appropriately sized array. Used + 1 to advance 
//pointer so the address of the pointer was not copied in and just the relevant
//struct values were
memcpy(structInfo, &dataPointer + 1, sizeof(MyDeviceData);
//If not using pointer to struct, then memcpy is easy
memcpy(structInfo, &deviceObject, sizeof(deviceObject));

需要注意的是chrisaycock和Sebastian Redl已经提到的,即适当地打包位并确保数组初始化使用可移植代码以确保其保存结构信息的正确大小。

structInfo 数组的大小计算并不是真正可移植的 - 尽管在实践中不太可能,但 MyDeviceData 的成员之间可能存在填充。

short structInfo[100 + 4 + 6];
memcpy(structInfo, devicePtr->powerLevel, 100*sizeof(short));
memcpy(structInfo + 100, devicePtr->unitInfo, 4*sizeof(short));
memcpy(structInfo + 100 + 4, devicePtr->unitSN, 6*sizeof(short));

这是便携式的。除此之外的任何事情可能都不是。如果你有一些常量来替换这些幻数,那当然会很好。

unsigned char structInfo[(100 + 4 + 6)*sizeof(short)];
unsigned char *tmpAddress = structInfo;
memcpy(tmpAddress , devicePtr->powerLevel, 100*sizeof(short)); 
tmpAddress +=100*sizeof(short);
memcpy(tmpAddress , devicePtr->unitInfo, 4*sizeof(short));
tmpAddress +=4*sizeof(short);
memcpy(tmpAddress , devicePtr->unitSN, 6*sizeof(short));
tmpAddress +=6*sizeof(short)

如果您尝试将其保存在字节数组中

相关文章: