2

我正在寻找一种将整个结构信息放入数组的方法。原因是我正在使用的函数需要读取一组信息。我不想调用这个函数 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 已经提到的,即适当地进行位打包并确保数组初始化使用可移植代码以确保其大小正确以保存结构信息。

4

2 回答 2

3

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

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

于 2013-06-13T16:28:54.390 回答
0
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)

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

于 2013-06-13T16:33:17.457 回答