Search code examples
carraysembeddedstring-literals

char array not recognized in function


I'm working on a project for a class. Embedded C-code. I'm attempting to create a char array of 5 strings that I declare globally so my LCD function can loop through the list easily. They could be declared as const but right now I just want it to build without issue.

Problem is I keep getting an 'undeclared' error in the function and 'conflicting types' error pointing at the declaration when I build. The declaration looks correct but I guess it's not. What am I missing? The undeclared error will probably fix itself once the declaration is sorted out.

     // Declared before main()
     char _cylinder_types[5];

    _cylinder_types[0] = "Blk";
    _cylinder_types[1] = "Wht";
    _cylinder_types[2] = "Stl";
    _cylinder_types[3] = "Alu";
    _cylinder_types[4] = "Err";

inside my lcd.c file:

void lcd_display_update(void){

  int i = 0;
  while(i<5)
    {
     lcd_write(0);
     lcd_position(lcd_TopLine,1);
     lcd_string("SORTED:");
     lcd_string(_cylinder_types[i]);
     lcd_write(':');
     lcd_write_Num_8(drop_number[i]);

     lcd_position(lcd_BotLine,1);
     lcd_string("UNSORTED:");
     lcd_string(_cylinder_types[i]);
     lcd_write(':');
     lcd_write_Num_8(queued_number[i]);

     mTimer(5000);
    }
     i++;
}

Solution

  • Just declare the array like

    char * _cylinder_types[5];
    ^^^^^^ 
    

    For example in this expression statement

    _cylinder_types[0] = "Blk";
    

    the string literal "Blk" is implicitly converted to an rvalue of the type char *.

    And you may not place these statements

    _cylinder_types[0] = "Blk";
    _cylinder_types[1] = "Wht";
    _cylinder_types[2] = "Stl";
    _cylinder_types[3] = "Alu";
    _cylinder_types[4] = "Err";
    

    outside any function.

    You could for example initially initialize the array like

     char * _cylinder_types[5] =
     {
         "Blk", "Wht", "Stl", "Alu", "Err"
     };
    

    If there are several compilation units in the project then the array should be declared in the header like

    extern char * _cylinder_types[5];
    

    and in some module defined like for example

     char * _cylinder_types[5] =
     {
         "Blk", "Wht", "Stl", "Alu", "Err"
     };
    

    The header must be included in each module where there is a reference to the array.

    Take into account that this statement

     i++;
    

    shall be inside the while loop.