I know how to do it with heap memory, but I try to get rid of any heap memory allocation in my code.
I cannot use any library which can help me, it means: <string>
for example.
How can I do it with using stack memory allocation?
int main(void) {
class Animal {
unsigned char nameLength;
unsigned char name[];
setName(unsigned char name[]) {
memcpy(this->name, name, this->length * sizeof(unsigned char));
}
}
Animal dog;
// The value '4' isn't constant, it depends on received data from socket
dog.nameLength = 4;
// Right now I know how many elements will be in dog.name array
unsigned char randomName[dog.nameLength];
// Here will be a for loop, but just for example:
randomName[0] = "B";
randomName[1] = "e";
randomName[2] = "n";
randomName[3] = "/0";
dog.setName(randomName);
// Expected output: dog.name = "Ben\0"
}
The for loop will look like:
unsigned char i;
for (i = 0; i < (dog.nameLength-1); i++) {
randomName[i] = packet[i];
}
randomName[i] = 0;