尝试将指针与struct一起使用时出错

Max*_*tax 0 c c++ struct pointers

我正在尝试将RGB值编码到结构中并且它工作正常但我得到一个例外,当我尝试运行访问该结构的函数时,我的结构是nullptr.这是代码:

struct Color {
    unsigned char R;
    unsigned char G;
    unsigned char B;
}*blue, *red, *green, *yellow, *purple, *pink, *brown;

void CreateColors()
{
    blue->R = 0;
    blue->G = 0;
    blue->B = 255;

    red->R = 255;
    red->G = 0;
    red->B = 0;

    green->R = 0;
    green->G = 255;
    green->B = 0;

    yellow->R = 255;
    yellow->G = 255;
    yellow->B = 0;

    purple->R = 133;
    purple->G = 87;
    purple->B = 168;

    pink->R = 255;
    pink->G = 0;
    pink->B = 191;

    brown->R = 168;
    brown->G = 130;
    brown->B = 87;

}
Run Code Online (Sandbox Code Playgroud)

如果你们可以告诉我我做错了什么或者使用更好的数据结构那会很棒.我是一个cpp类,我正在尝试巧妙地开始使用指针来加热它们.再次感谢.

当我尝试使用这些值时:

if (deg >= 0 && deg < boundaries[COAL_B])
{
    pixels[i][j][0] = blue->R;
    pixels[i][j][1] = blue->G;
    pixels[i][j][2] = blue->B;
}
Run Code Online (Sandbox Code Playgroud)

它会抛出同样的错误.

dbu*_*ush 5

你正在创建一系列指针struct Color,但你没有初始化它们,所以因为它们是在文件范围定义的,所以它们都被设置为NULL.然后尝试取消引用那些NULL指针.这会调用未定义的行为.

您应该改为定义这些结构的实例而不是指针:

struct Color {
    unsigned char R;
    unsigned char G;
    unsigned char B;
} blue, red, green, yellow, purple, pink, brown;
Run Code Online (Sandbox Code Playgroud)

然后将它们作为实例访问:

void CreateColors()
{
    blue.R = 0;
    blue.G = 0;
    blue.B = 255;

    red.R = 255;
    red.G = 0;
    red.B = 0;

    ...
Run Code Online (Sandbox Code Playgroud)

更好的是,摆脱初始化函数并在它们定义的位置初始化它们:

struct Color {
    unsigned char R;
    unsigned char G;
    unsigned char B;
};

struct Color blue = { 0, 0, 255}, red = { 255, 0, 0 }, green = { 0, 255, 0}, ...
Run Code Online (Sandbox Code Playgroud)