構造体情報全体を配列に入れる方法を探しています。この理由は、私が使用している関数には、読み取る情報の配列が必要だからです。この関数を X 回 (X は構造体にあるフィールドの数) 呼び出す代わりに、情報の塊全体を 1 つの配列に入れ、それを送信して書き込みます。
これは私が考えていたことです:
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 が既に述べたとおりであり、適切にビット パッキングし、配列の初期化で移植可能なコードを使用して、構造体情報を保持するための正しいサイズを確保していることを確認します。