[英]invalid cast from char* to int*
我试图在堆栈上使用char
缓冲区作为其他类型数据的存储。
作为测试,我从最基本的int
开始,但是无法编译chars指针到integer指针。
char buf[256];
int* l = static_cast<int*>(buf);
*l = 20;
我得到的错误是
error: invalid static_cast from type ‘char*’ to type ‘int*’
作为这些原始数据,我希望它能起作用:您知道此特定案例背后的机制是什么?
我通过使用reinterpet_cast
进行了整理,但我想使用static_cast
因为这应该更快。
您将需要重新解释演员表。 正确对齐的工作方式如下:
#include <memory>
std::aligned_storage<20 * sizeof(int), alignof(int)>::type storage;
int * p = reinterpret_cast<int *>(&storage);
for (std::size_t i = 0; i != 20; ++i)
{
::new (p + i) int(i); // or "p[i] = i;"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.