Cast int as byte array in C++
Solution 1
Use this:
(Byte*) &value;
You don't want a pointer to address 300, you want a pointer to where 300 is stored. So, you use the address-of operator &
to get the address of value
.
Solution 2
While Erik answered your overall question, as a followup I would say emphatically -- yes, reinterpret_cast
should be used rather than a C-style cast.
Byte* byteArray = reinterpret_cast<Byte*>(&value);
Solution 3
The line should be: Byte* byteArray = (Byte*)&value;
You should not have to put the (void *) in front of it.
-Chert
peace_within_reach
Updated on June 04, 2022Comments
-
peace_within_reach almost 2 years
I am trying to use implement the LSB lookup method suggested by Andrew Grant in an answer to this question: Position of least significant bit that is set
However, it's resulting in a segmentation fault. Here is a small program demonstrating the problem:
#include <iostream> typedef unsigned char Byte; int main() { int value = 300; Byte* byteArray = (Byte*)value; if (byteArray[0] > 0) { std::cout<< "This line is never reached. Trying to access the array index results in a seg-fault." << std::endl; } return 0; }
What am I doing wrong?
I've read that it's not good practice to use 'C-Style' casts in C++. Should I usereinterpret_cast<Byte*>(value)
instead? This still results in a segmentation fault, though.