user191776
user191776

Reputation:

Pointer to pointer interconversion

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?

Upvotes: 2

Views: 141

Answers (2)

pmg
pmg

Reputation: 108986

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.

Upvotes: 6

James McNellis
James McNellis

Reputation: 355307

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

Upvotes: 5

Related Questions