C++匿名结构指针赋值

C++ anonymous struct pointer assignment

本文关键字:指针 赋值 结构 C++      更新时间:2023-10-16

所以不,这不是最好的做事方法。但是,为了理论起见,如何成功地将指针值分配给匿名结构的指针?

#pragma pack(push,1)
    struct
    {
        __int16 sHd1;
        __int16 sHd2;
    } *oTwoShort;
#pragma pack(pop)
    oTwoShort = (unsigned char*)msg; // C-Error

生产:

错误 C2440:"=":无法从"无符号字符 *"转换为 ' *'

该示例假定msg本身是有效的指针。

这可能吗?既然你没有实际的类型,你甚至可以进行类型转换吗?

你可以得到decltype的类型:

oTwoShort = reinterpret_cast<decltype(oTwoShort)>(msg);

不过,这是在 C++11 中添加的,因此它不适用于较旧的编译器。Boost有一个大致相同的(BOOST_PROTO_DECLTYPE)的实现,旨在与旧的编译器一起工作。它有一些限制(例如,如果没记错的话,每个范围只能使用它一次),但无论如何它可能总比没有好。

我认为你必须使用 C++11 的decltype

oTwoShort = reinterpret_cast<decltype(oTwoShort)>(msg);
reinterpret_cast<unsigned char*&>(oTwoShort) = reinterpret_cast<unsigned char*>(msg);

但是,真的吗?

如前所述,您不能执行指针转换,但可以执行此操作:

memcpy(&oTwoShort,&msg,sizeof(void*));