How to initialize the array const unsigned char[] when declaring?

I write this:

 // RGB colors const unsigned char red[] = { 255,0,0 }, green[] = { 0,255,0 }, blue[] = { 0,0,255 }, black[] = { 0, 0 ,0 }, white[] = { 255,255,255 }; const unsigned char my_color[] = red; // <- error 

I get the error:

[Error] initializer fails to determine size of 'background_color'

I add an explicit size:

 const unsigned char background_color[3] = red; 

I get the error:

[Error] array must be initialized with a brace-enclosed initializer

Those. is it possible only through {} ? Why?

    2 answers 2

    In this case, you assign the pointer red to the array my_color, this is an error

     const unsigned char my_color[] = red; 

    Correctly assign like this

     const unsigned char * my_color = red; 

    or so

      const unsigned char * my_color[] = {red,green,blue,black,white}; 

    But if you want to copy the red array into the my_color array, then only direct copying

     my_color[0] = red[0]; my_color[1] = red[1]; my_color[2] = red[2]; 

      The main difficulty with you is that the assignment operation for arrays is not defined, and curly braces are needed to initialize the variable when it is declared.

      However, if you remember about the preprocessor, your initialization can be written like this:

       #define COLOR(r,g,b) { r, g, b } #define RED COLOR(255, 0, 0) #define GREEN COLOR(0, 255, 0) #define BLUE COLOR(0, 0, 255) #define BLACK COLOR(0, 0, 0) #define WHITE COLOR(255, 255, 255) const unsigned char red[] = RED, green[] = GREEN, blue[] = BLUE, black[] = BLACK, white[] = WHITE; const unsigned char my_color[] = RED; // <- No error int main() { // ... } 

      If you want to use color assignments in the executable part of the program, then you can go a little further and write, for example,
      (since structures can be assigned)

       // макросы для Ρ†Π²Π΅Ρ‚ΠΎΠ² ΠΎΡΡ‚Π°Π»ΠΈΡΡŒ ΠΏΡ€Π΅ΠΆΠ½ΠΈΠΌΠΈ struct color { unsigned char color[3]; }; const color red = RED, green = GREEN, blue = BLUE, black = BLACK, white = WHITE, my_color = RED; int main() { // Ρ‚Π΅ΠΏΠ΅Ρ€ΡŒ Ρ†Π²Π΅Ρ‚Π°ΠΌΠΈ ΠΌΠΎΠΆΠ½ΠΎ ΠΌΠ°Π½ΠΈΠΏΡƒΠ»ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ Ρ‚Π°ΠΊΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ color x, y = BLACK, z; x = (color)WHITE; y = (color)COLOR(1,2,3); z = my_color; z.color[1] = 200; } 
      • Why macros structures? - Qwertiy ♦
      • @Qwertiy, for beauty .... - avp