Search code examples
arraysencodingsyntaxarduinorecord

how to make an array containing multiple fields - Arduino


I am new to arduino and am trying to figure out how to create an indexable array of "records", i.e., each record containing fields, for instance

employee_number int

employee_first_name char string

employee_last_name char string

employee_age int

spouse_age int

etc.

The Arduino reference doesn't seem to address anything except a simple array.

I've searched here and the only thing I find is about someone trying to use an array to address a 4 x 4 keypad.

If Arduino can do such structures, I plan to suggest adding it to the Arduino Structures reference.


Solution

  • What you want is called a struct.

    struct EmployeeInfo{
      int number;
      char* first_name;
      char* last_name;
      int age;
    };
    
    EmployeeInfo employees[3] = {
      {1, "George", "Washington", 23},
      {2, "John", "Adams", 34},
      {3, "Thomas", "Jefferson", 43}
    };
    
    void setup() {
    
      Serial.begin(115200);
      for (int i=0; i<3; i++){
    
        Serial.print("Number ");
        Serial.println(employees[i].number);
        Serial.print("First Name ");
        Serial.println(employees[i].first_name);
        Serial.print("Last Name ");
        Serial.println(employees[i].last_name);
        Serial.print("Age ");
        Serial.println(employees[i].age);
      }
    }
    
    void loop() {
    
    }