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 use reinterpret_cast<Byte*>(value)
instead? This still results in a segmentation fault, though.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With