tags:

views:

72

answers:

2

Is it safe to convert an int pointer to void pointer and then back to int pointer?

main()
{
    ...
    int *a = malloc(sizeof(int));
    ...
    *a=10;
    func(a);
    ...
}

void func(void *v)
{
    int x=*(int *)v;
    ...
}

Is this a valid way of getting the integer value back in the function?

+5  A: 

It is "safe" insofar as the pointer resulting from the int => void => int conversion will be the same as the original pointer.

It is not "safe" insofar as it's easy to get wrong and you have to be careful (that said, this type of code is often necessary in C, since void* is often used as a form of generalization).

James McNellis
+6  A: 

Yes, it is safe. The Standard says so (6.3.2.3/1)

A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

pmg