0

How can I set an array pointer to null?

I have a pointer to a 3 int array that I am trying to set to null.

int (*EXCLUSIVE_COLOR)[3];

Per this link I was trying to set it to null upon initialization.
However this does not assign a null value to it. It assigns three 'random' integers to the array elements:

{128, 447, 451}

How can I make it point to a null or empty value?

3
  • 1
    if you assign null, test it for null, not read it
    – Juraj
    Jun 10, 2020 at 4:23
  • 3
    What were you expecting to get when you read a null pointer? That's undefined behavior. It could give you anything. If you want to make the thing pointed to zero then do that. That's not the same as assigning a null pointer.
    – Delta_G
    Jun 10, 2020 at 4:43
  • Does this answer your question? Assigning an element of a multidimensional array to a second array Jun 10, 2020 at 11:12

1 Answer 1

5

Here is a full example that shows you all thing things you have been asking over the past few days:

int colors[][3] = {
    {255, 0, 0},
    {0, 255, 0},
    {0, 0, 255}
};

#define NCOLOR (sizeof(colors) / sizeof(colors[0]))

int *EXCLUSIVE_COLOR = NULL;

void setup() {
    Serial.begin(115200);
    Serial.print("You have ");
    Serial.print(NCOLOR);
    Serial.println(" colors defined.");
    reportColor();
    EXCLUSIVE_COLOR = colors[2];
    reportColor();
    EXCLUSIVE_COLOR = NULL;
    reportColor();
}

void loop() {

}

void reportColor() {
    if (!EXCLUSIVE_COLOR) {
        Serial.println("Color is not set");
    } else {
        Serial.print("Color is set to ");
        Serial.print(EXCLUSIVE_COLOR[0]);
        Serial.print(",");
        Serial.print(EXCLUSIVE_COLOR[1]);
        Serial.print(",");
        Serial.println(EXCLUSIVE_COLOR[2]);
    }
}

You have an array of colours. You have a pointer that can point at a colour or at nothing. It starts off pointing at nothing. The code recognises that it's pointing at nothing and reports it. It gets assigned to a specific colour in your colours array. The code recognises that it's now a valid value and reports it. The pointer then gets pointed to nothing again. Again the code recognises that and tells you.

The result:

You have 3 colors defined.
Color is not set
Color is set to 0,0,255
Color is not set

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .