At first sight, I was planning to use sizeof(SessionInfo_t) or sizeof(session).
However, I found that the size of Arduino String (i.e., _userID) is variable, as it is dynamically allocated at runtime. Therefore, it may not be possible for the sizeof() operator to evaluate the size of the String at runtime.
The size of the struct instance would be used to write its raw data to a file using the SD.write(data, buf) function of the SD class, as suggested in this post.
Does anyone here a way of determining the exact size of each instance of the struct?
Thanks in advance.
p.s. To provide more context of what this is for, feel free could visit my GitHub repo.
You can't store a String type structure field to the file with raw write() function. The reason is the same as why you can't use the sizeof() function for determine the structure size - because the String use the dynamic allocation for store its contents.
Interesting solution...
But if I am to read the date from file, I have to parse the string using , as delimiter using String::subString() paired with String::indexOf(), then assigning the results to corresponding member variables. This could also be done using JSON much easier.
I planned to write raw date and do a reinterpret_cast<SessionInfo_t> for continence and efficiency. So, serialising the data when writing and then parsing it for reading would not be as optimal, I suppose.
Your suggestion is rather inspiring, though.
You may also put a pointer to your String in your struct. Then the size of your struct will be constant and you do not need to reserve 100 characters just to be sure...
This might get important if you make an array of structs.
Again, if you do not use a dynamic storage types you can just take the structure size like sizeof(SessionInfo_t). It will be correct considering optimisation and padding.
Regarding dynamic types - I don't have a correct answer.
Although this does give me constant size, it cannot be used to write to file, as the pointer is just an address represented by an integer rather than a string.
When the write-to-file operation is done, the struct will be out of scope and freed. So, the address extracted from the file will no longer be valid for retrieving the targeted String.