MaxAttax
MaxAttax

Reputation: 67

Getting error when trying to use pointer with struct

I am trying to code RGB values into a struct and it is working fine but I get an exception saying my struct was nullptr when I try to run a function that accesses that struct. Here is the code:

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;

}

If you guys could tell me what I am doing wrong or a better data structure to use that would be great. I am TA'ing a cpp class and am trying to subtly start using pointers to warm them up. Thanks again.

Also when I try to use these values like so:

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;
}

It throws the same error.

Upvotes: 0

Views: 292

Answers (2)

dbush
dbush

Reputation: 223872

You're creating a series of pointers to struct Color, but you're not initializing any of them, so because they're defined at file scope they are all set to NULL. You then attempt to dereference those NULL pointers. This invokes undefined behavior.

You should instead define instances of these structs instead of pointers:

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

Then access them as instances:

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

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

    ...

Better yet, get rid of the initialization function and initialize them at the point they're defined:

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}, ...

Upvotes: 5

Kon
Kon

Reputation: 4099

You declare a pointer to a structure but never allocate memory for it. When you access it's members, you're dereferencing a null pointer.

Upvotes: 0

Related Questions