Hi, I have a custom type that I'd like to serialize as a char array:
typedef struct network {
char SSID[50];
char PASS[50];
} network_t, *network_p;
typedef struct nvs {
network_p* networks;
uint8_t items;
} nvs_t, *nvs_p;
adding some items:
nvs_t _1 = nvs_t();
_1.items = 2;
_1.networks = (network_p*)malloc( _1.items * sizeof(network_p) );
_1.networks[0] = (network_p)malloc( sizeof(network_t) );
_1.networks[1] = (network_p)malloc( sizeof(network_t) );
strcpy(_1.networks[0]->SSID, "alma");
strcpy(_1.networks[0]->PASS, "körte");
strcpy(_1.networks[1]->SSID, "szilva");
strcpy(_1.networks[1]->PASS, "narancs");
nice until here. My serialization purpose is:

I tried to copy a whole network_t struct in one pass but it didn't work:
unsigned char foo[sizeof(uint8_t)+_1.items*sizeof(network_t)] = {0};
unsigned char *ptr = foo;
memcpy(foo, &(_1.items), sizeof(uint8_t));
for(int i=0, offset = sizeof(uint8_t);i<_1.items;i++, offset +=sizeof(network_t)) {
memcpy(foo + offset, &(_1.networks[i]), sizeof(network_t));
}
The working version is:
unsigned char foo[sizeof(uint8_t)+_1.items*sizeof(network_t)] = {0};
unsigned char *ptr = foo;
memcpy(foo, &(_1.items), sizeof(uint8_t));
for(int i=0, offset = sizeof(uint8_t);i<_1.items;i++, offset +=50) {
strcpy((char *)(foo + offset), (char *)&(_1.networks[i]->SSID));
offset +=50;
strcpy((char *)(foo + offset), (char *)&(_1.networks[i]->PASS));
}
It is actually working but I don't like it. Wiring the offset is ugly, to recover the individual elements in this way is ugly, too.
Is there a nicer solution?