Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy to void* pointer

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.

like image 868
Yakov Avatar asked Sep 16 '25 01:09

Yakov


1 Answers

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.

like image 126
dbeer Avatar answered Sep 19 '25 06:09

dbeer