0

How can I set an array pointer tonull?

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

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 anull orempty value?

3
  • 1
    if you assign null, test it for null, not read itCommentedJun 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.CommentedJun 10, 2020 at 4:43
  • Does this answer your question?Assigning an element of a multidimensional array to a second arrayCommentedJun 10, 2020 at 11:12

1 Answer1

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 setColor is set to 0,0,255Color is not set
answeredJun 10, 2020 at 10:44
Majenko's user avatar

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.