问题
I am reading a book on pointers named "understanding and using c pointers"
When it comes to void *
it says
It has two interesting properties:
- A pointer to void will have the same representation and memory alignment as a pointer to char.
What am confused about is isn't the memory of all the pointers same? They why instead of writing void* is same as normal pointer it explicitly mentioned char pointers? Will really appreciate any help
回答1:
On most common architectures, pointer to any data type has the same representation, while pointer to function may differ. However, it's not a requirement, so it's possible to create valid C implementation, which uses different pointers for different data types. The reason behind this is that C standard tends to describe only crucial requirements, leaving a lot of freedom for possible implementations. Here is what standard says:
A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.
If you're curious to see examples of systems with different sizes for different data types, this question mentions these wonderful examples
回答2:
I think the point here is "memory alignment", not "memory size".
Yes, all pointers have same size of memory. But they may have different limitation for memory alignment.
For example, on some platforms, a "32-bit int" pointer must point to the address which should be times of 4 bytes. It cannot point to, e.g. 0x100001 or 0x100003.
But a "8-bit char" pointer can point to any address. So does a "void" pointer.
So it said that.
来源:https://stackoverflow.com/questions/43092033/void-will-have-the-same-representation-and-memory-alignment-as-a-pointer-to-cha