I want to copy data from different variables and put it together in an array so that I can process it further.
I have studied direct assignment and memcpy method and think memcpy is used to copy complete buffer and not individual elements. Also I think it may take time and waste CPU cycles to use memcpy for individual bytes.
Can you please let me know from below example what should be used in such case since it is running in multithreaded environment(different example) and varibles may change?
#include <stdio.h>
#include <stdint.h>
int main()
{
printf("Direct assign method\n");
uint8_t pack_id = 123;
uint8_t pack_age = 76;
uint8_t pack_cmd = 30;
uint8_t cus_data[3] = {0};
cus_data[0] = pack_id;
cus_data[1] = pack_age;
cus_data[2] = pack_cmd;
printf("Memcpy method\n");
pack_id = 112;
pack_age = 89;
pack_cmd = 25;
memcpy(&cus_data[0], &pack_id, sizeof(pack_id));
memcpy(&cus_data[1], &pack_age, sizeof(pack_age));
memcpy(&cus_data[2], &pack_cmd, sizeof(pack_cmd));
return 0;
}
memcpyfor one byte would probably take more time than direct assignment.memcpy()looks inappropriate here, indeed.memcpyis a standard library function and the compiler is allowed to optimize as it pleases.