C++匿名结构指针赋值
C++ anonymous struct pointer assignment
所以不,这不是最好的做事方法。但是,为了理论起见,如何成功地将指针值分配给匿名结构的指针?
#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*));
相关文章:
- 错误:在为指针赋值时,void值没有被忽略
- 关于 c++ 函数中指针赋值的简单问题
- 链表指针赋值为什么我们不能直接将尾巴分配给 temp 而不是尾巴>尾巴下一个
- 为什么通过指针赋值常量没有效果?
- 复制构造函数中的指针赋值
- C++ 指针赋值运算符重载(不仅是对象赋值,还有指针赋值)
- 从字符串数组打印其中一个字符串时出现空指针赋值错误
- 为字符串指针赋值
- 动态指针赋值c++
- std::wstring指针赋值C++
- C++匿名结构指针赋值
- 为指针赋值而不赋值
- 此指针赋值应生成段错误
- 指向指针赋值的指针
- 哪个指针赋值更好(C++)
- <T>unique_ptr.get() 方法在使用原始指针赋值时调用析构函数?
- 为用soap_alloc创建的std::string指针赋值
- 为什么函数头的更改会导致指针赋值不起作用
- 64位c++指针赋值
- 在函数中将指针赋值到不同的地址