Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Try to copy uint8_t number into uint8_t array with memcpy

I’m trying to use memcpyto copy an uint8_t to an uint8_t[] but it’s doesn’t work here is what I’ve tried

uint8_t mess[16];
uint8_t my_number = 1;
memcpy(mess, &my_number, sizeof(my_number)); 

When I print my mess I have nothing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

SerialUSB.println(char *)mess)

SerialUSB.println requires a null terminated string, but the below does not initialize the array so the values in the array are indeterminate:

uint8_t mess[16];

Reading indeterminate vales makes the program have undefined behavior so initialize it:

uint8_t mess[16]{}; // now initialized with 0:s

Further, memcpy is unnecessary here:

uint8_t my_number = 1;
memcpy(mess, &my_number, sizeof(my_number)); 

It’s the same as

mess[0] = my_number;

And it’s unlikely that you actually wanted the character with value 1 when using println since it’s an "invisible" character (in ASCII at least), but instead wanted the character '1':

mess[0] = static_cast<uint8_t>('1');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading