user287474 user287474 - 8 months ago 53
C Question

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