C语言 c:空隙大小*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6908686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:17:25  来源:igfitidea点击:

c: size of void*

cvoid-pointers

提问by facha

I'm a bit confused with a void* pointer in C. Especially after reading this question: Is the sizeof(some pointer) always equal to four?, where one person says there is no guarantee that sizeof(int *) == sizeof(double *)

我对 C 中的 void* 指针有点困惑。尤其是在阅读了这个问题之后:Is the sizeof(some pointer) always equal to 4?,其中有人说不能保证 sizeof(int *) == sizeof(double *)

My question is: is there a guarantee of sizeof(void*) >= sizeof(any other pointer type)? In other words, can I always assign a some_type* pointer to a void* pointer and then get it back as some_type*?

我的问题是:是否有 sizeof(void*) >= sizeof(任何其他指针类型)的保证?换句话说,我可以总是将 some_type* 指针分配给 void* 指针,然后将其作为 some_type* 取回吗?

回答by cnicutar

Only data pointers. void *can hold any data pointer, but not function pointers.

只有数据指针。void *可以保存任何数据指针,但不能保存函数指针。

Here is a C FAQ.

这是C 常见问题解答

void *'s are only guaranteed to hold object (i.e. data) pointers; it is not portable to convert a function pointer to type void *. (On some machines, function addresses can be very large, bigger than any data pointers.)

void *'s 只保证持有对象(即数据)指针;将函数指针转换为 void * 类型是不可移植的。(在某些机器上,函数地址可能非常大,比任何数据指针都大。)

As for the first part, yes, different types can have pointers of different sizes:

至于第一部分,是的,不同的类型可以有不同大小的指针

回答by unpythonic

The value stored in the pointer is an address to memory. If you're on a 32-bit system, that pointer into memory is going to be 32 bits (or four bytes) long. If you're on a 64-bit system, that pointer into memory is going to be 64 bits (or eight bytes) long.

存储在指针中的值是内存地址。如果您使用的是 32 位系统,那么指向内存的指针将是 32 位(或四个字节)长。如果您使用的是 64 位系统,那么指向内存的指针将是 64 位(或 8 个字节)长。

The size of the data that holds the location in memory has nothing to do with the size of the data represented at that location in memory.

保存内存中该位置的数据大小与内存中该位置表示的数据大小无关。

As for how a char *differs from a double *, the char *can point to any location, but the double *has to point to something along an eight-byte boundary. Larger data has to be aligned according to the rules of the processor you're on. So, pointers to small data are not generally compatible with pointers to large data (e.g. you shouldn't point a double *pointer to a char *address); but you're save going in the other direction (e.g. you can point a char *pointer to a double *address).

至于 achar *与a 的不同之处double *,thechar *可以指向任何位置,但 thedouble *必须指向沿八字节边界的某些内容。较大的数据必须根据您所在处理器的规则进行对齐。因此,指向小数据的指针通常与指向大数据的指针不兼容(例如,您不应将double *指针指向char *地址);但是您可以节省向另一个方向前进(例如,您可以指向char *一个double *地址的指针)。