Reputation: 313
I don't know it that's possible, probably not - but maybe
What I'm trying to achieve is like the following, just for n
sized chars array:
*(__int64*)(address) = 0x1337;
this works just fine for type __int64
or __int32
or float
and many more, what I want to do is
*(char[8]*)(address) = [0x37, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
Upvotes: 0
Views: 1059
Reputation: 238321
Is it possible to cast to fixed sized array in cpp?
No, it is not possible to cast to an array type in C++. But you can cast to a pointer to array for example, which I'm guessing may be what you're trying to do.
*(char[8]*)(address)
I suppose that you're trying to cast address
into a pointer to an array. That is not the correct syntax for pointer to array. This is correct: *(char(*)[8])(address)
Other problem is that arrays are not assignable. What you can do instead is assign each element of the array. There are standard algorithms to do loops like this. In this case, a simple solution is to declare an array with those elements, and copy from that array to the one pointed by address
. Example:
char* ptr = *static_cast<char(*)[8]>(address);
constexpr std::array data{0x37, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
std::copy(std::begin(data), std::end(data), ptr);
A way to assign arrays is to wrap them inside a class, and use the assignment operator of that class. In fact, std::array
template used in the above example is exactly such wrapper. If you used that type for your original array, then you could simply do:
std::array<char, 8> array;
void* address = &array; // imagine that for some reason you are forced to use void*
*static_cast<std::array<char, 8>*>(address)
= {0x37, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
P.S. Avoid C-style casts.
Upvotes: 2