开发者

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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜