在C++中将int转换为字节数组

pea*_*ach 4 c++ byte casting segmentation-fault

我正在尝试使用实现安德鲁·格兰特建议的LSB查找方法来回答这个问题:设置的最低有效位的位置

但是,它导致了分段错误.这是一个展示问题的小程序:

#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;  
}  
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?
我已经读过在C++中使用'C-Style'强制转换是不好的做法.我应该用reinterpret_cast<Byte*>(value)吗?但是,这仍会导致分段错误.

Eri*_*rik 12

用这个:

(Byte*) &value;
Run Code Online (Sandbox Code Playgroud)

您不希望指向地址300的指针,您想要指向存储300的指针.因此,您使用address-of运算符&来获取地址value.


ild*_*arn 8

虽然Erik回答了你的整体问题,但作为一个后续内容我会强调说 - 是的,reinterpret_cast应该使用而不是C风格的演员.

Byte* byteArray = reinterpret_cast<Byte*>(&value);
Run Code Online (Sandbox Code Playgroud)