简体   繁体   中英

invalid cast from char* to int*

I am trying to use a buffer of char on the stack as storage for some other type of data.

As test I started with the most basic int but casting pointer of chars to pointer of integer doesn't compile.

 char buf[256]; 
 int* l = static_cast<int*>(buf);
 *l = 20;

The error I got is

error: invalid static_cast from type ‘char*’ to type ‘int*’

Being these primitive data I was expecting this to work: do you know what is the mechanics behind this specific case?

I sorted out by using reinterpet_cast but I'd like to use static_cast as this last should be more fast.

You will need a reinterpret cast. Here's how it works with proper alignment:

#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;"
}

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