Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast int as byte array in C++

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.

like image 877
peace_within_reach Avatar asked Nov 29 '22 17:11

peace_within_reach


1 Answers

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.

like image 197
Erik Avatar answered Dec 04 '22 21:12

Erik