Say I am given a void* data array, and asked to populate it with info of 2 different datatypes: an array of int's and a string.
void* data;
int numbers[9];
char* title;
I understand that to input the numbers into the data array, I need to typecast it like this:
memcpy((int*)data, numbers, sizeof(numbers));
But what do I do if I want to put title in the address after numbers gets copied into data?
Thanks in advance.
No, there's no need to type cast, since memcpy() works with void *:
memcpy(data, numbers, sizeof numbers);
Also no need for ()s with sizeof when applied to anything that is not a type name.
For the second part, you need to compute the address:
memcpy((char *) data + sizeof numbers, title, 1 + strlen(title));
Here I assume that title is a 0-terminated string. The cast of data to char * is necessary since you can't do pointer arithmetic with void *.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With