copy to void* pointer

c, copy, void-pointers

Solution

If you are certain that the memory referenced by the void pointer is an int, then you can be confident in

*(int *)data = r;

However a better general solution is:

memcpy(data, &r, sizeof(int));

This way you don't have to worry about byte alignment or other potential gotchas.

Problem

I have a function `getData(void* data)` which should copy to data some internal calculated values for example `int r = getRadius();` r should be copied to data ,and is such a way returned from function getData what is the correct way to do it? I tried `*(int*)data = r;` but I am not sure this is a best solution.

Original source