0

I have two arrays. The first array is a multidimensional array holding color values.

The 2nd array stores an active color from the 1st array. How can I assign an element from the multidimensional colors array to the 2nd EXCLUSIVE_COLOR array?

int colors[][3] = {
  { 255, 0, 0 },   
  { 0, 255, 0 },   
  { 0, 0, 255 },   
  { 253, 7, 210 }  
};
int EXCLUSIVE_COLOR[3] = {0};

I tried the following but neither seemed to work:

    EXCLUSIVE_COLOR = { 
      colors[0][0], 
      colors[0][1], 
      colors[0][2]
    };
    // error: assigning to an array from an initializer list

    EXCLUSIVE_COLOR = colors[0];
    // error: invalid array assignment
4
  • what is the type of EXCLUSIVE_COLOR. you want a pointer to the array or a copy of the array?
    – Juraj
    Jun 8, 2020 at 9:16
  • Either one would work. EXCLUSIVE_COLOR is a 3 element int array. Jun 8, 2020 at 9:26
  • int* EXCLUSIVE_COLOR = colors[0];. and then you can use EXCLUSIVE_COLOR[i]
    – Juraj
    Jun 8, 2020 at 9:31
  • Why do you use a two-dimensional array, if you have a one-dimensional array of Color elements in reality? Jun 8, 2020 at 12:01

2 Answers 2

1

You can copy the array:

EXCLUSIVE_COLOR[0] = colors[0][0];
EXCLUSIVE_COLOR[1] = colors[0][1];
EXCLUSIVE_COLOR[2] = colors[0][2];

but this doesn't work in an initialization.

Alternatively, you can declare EXCLUSIVE_COLOR as a pointer to an array of 3 integers:

int (*EXCLUSIVE_COLOR)[3]; // pointer to array 3 of int

Then you can have this point to a row of the 2D array, either by assigning the pointer or in the initialization:

int (*EXCLUSIVE_COLOR)[3] = &colors[0];  // initialization

// Later in the program:
EXCLUSIVE_COLOR = &colors[1];

Note that when using this pointer, you will have to explicitly dereference it:

for (int i = 0; i < 3; i++)
    Serial.println((*EXCLUSIVE_COLOR)[i]);

Edit: As pointed out by Juraj in a comment, you can instead make EXCLUSIVE_COLOR a pointer to int. In this case you will make it point to the first element in the row you want:

int* EXCLUSIVE_COLOR = &colors[0][0];

One nice thing of this approach is that you can use the “decay to pointer” feature of the language to simplify the syntax:

int* EXCLUSIVE_COLOR = colors[0];

// Later
Serial.println(EXCLUSIVE_COLOR[i]);
2
  • a pointer to pointer? it doesn't look right
    – Juraj
    Jun 8, 2020 at 9:37
  • 1
    @Juraj: It's not a pointer to pointer, it's a pointer to an array. Jun 8, 2020 at 9:39
0

Use arrays only where appropriate:

struct Color {byte r, g, b;};
const Color colors[] = {
  {0,255,0},
  {255,0,0}
};
const Color red = colors[1];

This works without const as well. But you should consider using const wherever possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.