#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    30
    Rep Power
    2

    Type of pointer variables


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

    Code:
    int* pointerVariable;
    int x;
    
    pointerVariable = &x;
    By the way is the asterisk part of the pointerVariable type?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,392
    Rep Power
    1871
    > 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.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,113
    Rep Power
    1803
    Originally Posted by MiguelC
    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 ;)

IMN logo majestic logo threadwatch logo seochat tools logo