Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting in C - Ints and Char*

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.

like image 656
user287474 Avatar asked Dec 05 '25 21:12

user287474


1 Answers

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 *.

like image 122
unwind Avatar answered Dec 08 '25 12:12

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!