它是合法的,通过一个空白修改任何数据指针** [英] Is it legal to modify any data pointer through a void **

查看:137
本文介绍了它是合法的,通过一个空白修改任何数据指针**的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是合法的通过访问指针类型无效**

Is it legal to access a pointer type through a void **?

我看过了标准的引用上的指针别名,但我仍然在这是否是合法的C与否不确定:

I've looked over the standards quotes on pointer aliasing but I'm still unsure on whether this is legal C or not:

int *array;
void **vp = (void**)&array;
*vp = malloc(sizeof(int)*10);

简单的例子,但它适用于更复杂的情况,我看见了。

Trivial example, but it applies to a more complex situation I'm seeing.

看来,因为我访问它不会是一个合法的为int * 通过其类型不是一个变量为int * 的char * 。我不能对这个简单的结论。

It seems that it wouldn't be legal since I'm accessing an int * through a variable whose type is not int * or char *. I can't come to a simple conclusion on this.

相关阅读:

  • Does C have a generic "pointer to a pointer" type?
  • C-FAQ question 4.9

推荐答案

指向不同的类型可以有不同的大小。

Pointer to different types can have different sizes.

您可以存储指向任何类型的成无效* 然后你就可以恢复回来,但这只是意味着一个无效* 必须大到足以容纳所有其他的指针。

You can store a pointer to any type into a void * and then you can recover it back but this means simply that a void * must be large enough to hold all other pointers.

治疗是持有 A变量int * 像它的确是一个无效* 是相反,在一般情况下,不允许的。

Treating a variable that is holding an int * like it's indeed a void * is instead, in general, not permitted.

还要注意的是在做类型转换(例如,转换为为int * 的malloc 的结果)是完全不同的东西从包含处理的内存区域为int * 像它包含无效* 。在第一种情况下,如果需要编译器的转换通知,在第二,而不是你提供虚假信息的编译器。

Note also that doing a cast (e.g. casting to int * the result of malloc) is something completely different from treating an area of memory containing an int * like it's containing a void *. In the first case the compiler is informed of the conversion if needed, in the second instead you're providing false information to the compiler.

在X86然而他们通常相同的尺寸和你是安全的,如果你只是用数据指针玩(函数指针可能会有所不同,虽然)。

On X86 however they're normally the same size and you're safe if you just play with pointers to data (pointers to functions could be different, though).

关于别名通过无效* 的char * 可能变异的任何对象,这样做的编译器的任何写操作必须考虑混叠越好。
然而,在这里你的榜样你通过一个无效** (另一回事),写作和编译器可以随意地忽略潜在的抗锯齿效果,以 INT *

About aliasing any write operation done through a void * or a char * can mutate any object so the compiler must consider aliasing as possible. Here however in your example you're writing through a void ** (a different thing) and the compiler is free to ignore potentially aliasing effects to int *.

这篇关于它是合法的,通过一个空白修改任何数据指针**的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆