This answer comes with an interesting statement - "on machines where int*
is smaller than a char*
". (let's exclude pointers to functions)
Is it possible for pointers to different types to have different sizes? Why would this be useful?
This answer comes with an interesting statement - "on machines where int*
is smaller than a char*
". (let's exclude pointers to functions)
Is it possible for pointers to different types to have different sizes? Why would this be useful?
Yes, it's entirely possible. On some machines, a pointer to a byte contains two values: A pointer to the WORD address of the memory word containing the byte, and a "byte index" that gives the position of the byte within the word. E.g. on a 32-bit machine, the "byte index" is 0..3.
This would require more storage space than a "int *", which is just a pointer to the relevant word.
On word addressed machines a char*
might need to contain part-word info, making it larger than an int*
.
The standard allows this, not to rule out implementations on such hardware (even though that is even more rare now than when C89 was designed).
The language-lawyer tag means that you are asking about C++ and its compliant implementations, not some specific physical machine.
I'd have to quote the entire standard in order to prove it, but the simple fact is that it makes no guarantees on the result of sizeof(T*)
for any T
, and (as a corollary) no guarantees that sizeof(T1*) == sizeof(T2*)
for any T1
and T2
).
Yes, pointers aren't guaranteed to have the same size, although on most modern architectures they are, in practice.
One point where this can be useful is when one concerns data vs. function pointers. Historically, function pointers (that are used to essentially jump to certain parts in the executable code) needed so-called "far pointers" which are wider than data pointers.
I can imagine a machine where it makes sense to assume that the memory needs for int
arrays are going to be far less than the memory needs for char
arrays.
One may specify, for instance, that an implementation is not going to use more than 10 dynamically allocated integers, but is free to allocate many char
arrays. In this case, one byte may suffice for an int*
, while a char*
needs to be four bytes or more.
That's a theoretical vision.