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