简体   繁体   中英

Dereferencing void pointer to assign value to struct

I have several structs containing various combinations of parameters. I wrote a function that takes a void pointer reference to the structs (there are several different types), and writes information from the data parameter into them. Here's the function below:

void SubModelBase::writeDataStruct(byte msgID, void *ptr, QByteArray data)
{
    *(byte*)ptr[0] = msgID;
    *(byte*)ptr[1] = data.length();

    for (int i = 2; i < data.length(); i++)
    {
        *(byte*)ptr[i] = data.at(i);
    }
}

The void *ptr is the reference to the struct that I want to write the data into but I'm having issues deferencing the pointer so I can write into it. I'm sure I'm just missing something silly in my syntax here but I'm not seeing it at the moment...

EDIT:

Ok, I rewrote the function to first cast the void pointer to a byte pointer before assigning values:

void SubModelBase::writeDataStruct(byte msgID, void *ptr, QByteArray data)
{
    byte* structData = (byte*)ptr;
    structData[0] = msgID;
    structData[1] = data.length();

    for (int i = 0; i < data.length(); i++)
    {
        structData[i + 2] = data.at(i);
    }
}

Not tested yet but now it at least compiles. I did it this way because there are over 30-40 different structs that need to have data filled in them and I needed a single function that can handle the operation easily without knowing the details of each struct. However, if there is a better way to approach the problem, I'm definitely open to ideas.

EDIT 2: Fixed logic error in loop

您似乎在寻找一个模板,以便编译器在您需要时创建正确的方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM