【问题标题】:Putting Struct information into one big array将结构信息放入一个大数组中
【发布时间】:2013-06-13 16:24:52
【问题描述】:

我正在寻找一种将整个结构信息放入数组的方法。原因是我正在使用的函数需要读取一组信息。我不想调用这个函数 X 次,其中 X 是我在结构中拥有的字段数,我想将整个信息块放入一个数组中并将其发送出去以进行写入。

这就是我的想法:

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 已经提到的,即适当地进行位打包并确保数组初始化使用可移植代码以确保其大小正确,以保存结构信息。

【问题讨论】:

标签: c++ c arrays struct


【解决方案1】:

您对 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));

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

【讨论】:

  • 作为补充评论,我建议重载函数以获取您的结构类型的参数,并将此逻辑放在那里,而不是 main。这将使您的主循环保持简洁明了,并阐明这种有些不寻常的逻辑的目的。
  • 感谢您的可移植性提示,我会阅读更多内容并进行更改。但是,如果我有一个结构,其中包含 20 个包含各种信息的数组,那么看起来必须执行 20 个 memcpy 调用,这并不吸引人。
  • 您也许可以使用 short* 执行类似的逻辑,并将您的设备指针转换为短指针......但这可能会在提到的填充场景下导致混乱,并且由于其他原因而不好!
【解决方案2】:
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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多