Copy String to Struct - I am confused


#1

Hi, I am attempting to convert a Arduino library that makes extensive use of structs and my project receives data as Strings. I am struggling to work out how to copy the string to the struct and then successfully reference the struct members. I have tried a few variations, some won’t build and generate
errors converting void to const void, others compile but the data within the struct can’t be successfully read.

Code below is a simple example of what I am wanting to achieve. Any help would be greatly appreciated.

Thanks.

typedef struct  {
  uint8_t   FirstName[4];  // 0
  uint8_t   Age;       // 3
  uint8_t   BirthMonth;     // 4
} PersonRecord;

PersonRecord personDataSet;

String PersonData;

void setup() {

    PersonData = "DEAN41";

    memcpy(personDataSet, PersonData, 6);

    Particle.publish("DIAG", String::format("Name %c%c%c%C, Age: %i, Birth month:%i", personDataSet.FirstName[0],personDataSet.FirstName[1],personDataSet.FirstName[2],personDataSet.FirstName[3],personDataSet.Age, personDataSet.BirthMonth ));
    
}

void loop() {

}

#2

String is an object type and the address you get when directly referencing it is not the content of the string but the static portion of the object.

If you want to reference the actual string content you should use one of the methods provided by the String class (i.e. String::getBytes())

Also copying data into a struct like that may not always render the result you expect.
You need to consider memory packing. On 32 bit systems it’s usually faster to align data fields on 32bit boundaries and hence you may find that your individual fields may not be stored in a consecutive fashion but with some padding between to have the next field align again.
Even if that code works on one platform, it won’t be guaranteed to work on another unless you explicitly state that your struct should be packed (see here).
Generally it’s better practice to assign individual fields individually.

Also when you write 41 into Age and BirthMonth do you expect the values to be only single digits or should you actually mean Age == 52 and an invalid month of 49? The numeric values of the ASCII symbols 4 and 1 are 52 and 49 respectively.

BTW, please use Particle.publish() with the PRIVATE scope limiter :wink:
You don’t want to publish your diagnostics to the public. When everybody does that that “channel” will be flooded with tons of data with no use to anybody but one person (if that).