Re: pointer to array types
On Mar 22, 11:15 am, "Paul" <pchris...@yahoo.co.uk> wrote:
You are inconsistent and innacurate because below you state: "it is
certainly not a pointer to an array".
Above you say that "one can say it's pointing to an array", you don't seem
to know what it's pointing to.
Again, I don't post this for the benefit of Paul, but for everyone
else. I have been not terribly satisfied with the answers to this
given thus far, so I post for the benefit of someone new to C++
reading this.
The statement "x is a pointer" is a statement about the type of the
variable and object named by the identifier "x".
The statement "x points to y" is a statement about the runtime value
of the pointer object x.
For example:
int* x = new int[10];
The following are all true:
- x is a pointer.
- x is a pointer to int.
- x is not a pointer to (int) array.
- x is not an (int) array.
- x points to an int.
- x points to an int array. This last statement is a little loose in
terminology, but most people would not normally consider it incorrect,
and it would be rather clear what was stated. Still, it's important to
understand the difference - under a particularly pedantic and
technical reading it does point to an int, and it does not point to an
int array, because that is the interpretation of the bit value under
its type of "pointer to int". This is despite that the "pointer to
first element" and "pointer to array" commonly have the same bit
value.
Related:
#include <iostream>
using namespace std;
template <typename T>
ostream& print_bit_representation(ostream& out, T const& x)
{
for (size_t i=0; i<sizeof(T); ++i)
out << (int)*(reinterpret_cast<unsigned char const*>(&x) + i) <<
" ";
return out;
}
int main()
{
typedef int (T)[10];
T x; //aka int x[10];
int* y = x;
T* z = &x; //aka int (*z)[10];
print_bit_representation(cout, y);
cout << endl;
print_bit_representation(cout, z);
cout << endl;
}
On my computer, the output is:
4 255 24 0
4 255 24 0
It doesn't have to be the same bit value, nor would I ever write code
to rely on such a thing, but as a matter of fact I expect that it
commonly is.
Finally, the property "x points to y" can be strictly defined as "the
pointer object x has the value of the address of the object y", but I
don't think most people use such a strict definition. Most people use
a looser definition. For example:
struct A {};
struct B : {};
B b;
A* a = &b;
I think that most people would not have a problem with saying "a
points to b", even though by the aforementioned strict definition of
"points to", a does not point to b. a doesn't hold the address of the
b object. It holds the address of the A sub-object. This difference is
incredibly important when explaining why reinterpret_cast-ing or C-
style casting willy nilly with virtual inheritance or multiple
inheritance doesn't do what you might naively expect it to.