开发者

c: size of void*

I'm a bit confused with a void* pointer in C. 开发者_JAVA百科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 *)

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*?


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

Here is a C FAQ.

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

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


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.

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜