> Why does a pointer variable have to be of the same type as the variable it is pointing to?
So you don't get complete garbage (or a crash), when you do something like
*pointerVariable = 42;

Yes, you can cast your pointer to make an int pointer point at anything you like, and the compiler will duly generate the code to write an int-sized block of memory over whatever it is you happen to be pointing at.

> By the way is the asterisk part of the pointerVariable type?
If you say
int *intPtr, intVar;
then intVar is just an integer, NOT a pointer to an integer.
In that sense, the * binds more closely to the name rather than the type.

Why does a pointer variable have to be of the same type as the variable it is pointing to?

So that the compiler is better able to detect and report possible errors in your code. all sorts of bugs could arise if you inadvertently assigned one type to another. If you are deliberately assigning mismatched incompatible types you can "take control" and use a cast... but you had better know what you are doing!

In the general case the use of a void pointer as an intermediate for communicating "address to undetermined type" can be used.

Originally Posted by MiguelC

By the way is the asterisk part of the pointerVariable type?

Yes it is - that is how the compiler and the debugger handle pointer types. Syntactically as @salem has pointed out, it might make sense to place the * immediately adjacent to the symbol name, but I would argue that you should not declare multiple variables in a single statement in the first place (to avoid the ambiguity altogether rather than attempt to resolve it by layout) and therefore always place it adjacent to the type.

Three styles prevail:

Code:

int* p1 ;
int *p2 ;
int * p3 ;

The last is for people who really cannot make up their mind and has little merit whatsoever ;)