a C/C++ pointer variable has a target-data-type

(see also post on void ptr)
Consider a simple declaration

  int *intp;

Q1: If a pointer variable holds an address, why is it necessary (to compilers) to attach a data type to a pointer variable? From then on the intp variable will be treated always, always as a pointer to a __int__.
A1: when an address is assigned to this pointer, the address is treated as the starting address of a block of memory. An essential info is the size of the block. A wild compiler can treat 8 bytes starting at that address as an object, or 888888 bytes!
A1: every operation on “intp” must be valid for integers. Compilers must check that.

To further answer this question, consider a more basic question —

  int intVar;

Q2: why is it necessary to attach a data type to a nonref variable? From then on the intVar variable will be treated always, always as an int.
A2: I think compiler (yes compiler) must allocate the right amount of memory for the object
A2: compiler must access-check every operations on it. Compiler won’t allow concatenation for an int, right?

Q3: how large is the intp variable itself, if it has to hold both the address and the type?
A3: 32 bits. I believe the data type is not “carried” by the intp variable so doesn’t increase its size. I think it may be a compile-time information rather than runtime information. At runtime, the data type of the pointer is lost and not checked by anyone

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s