Thread: Pointer/Variable

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    26

    Pointer/Variable

    Code:
    int *x, y;
    x = y;
    Why does that give an error?

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    That statement declares x as an integer pointer and y as an integer (not a pointer) which are not the same. Perhaps you meant:
    Code:
    int *x, *y;
    ...
    x = y;
    ...which would declare both x and y as pointers.

    [edit]y should actually point to something valid before you do such an assignment.[/edit]
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    This is also a reason to prefer declaring one pointer per statement:

    Code:
    int* x;
    int* y;
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    Registered User
    Join Date
    Nov 2009
    Posts
    82
    This should make it clear.

    Code:
    int *x, y; == int *x; int y;
    x = &y;
    
    ---
    
    int *x, *y;
    x = y;
    
    ---
    
    int x, y;
    x = y;
    
    ---
    
    int* x, y; == int *x, y; == int * x, y;
    Last edited by since; 12-01-2009 at 03:22 PM.

  5. #5
    Registered User
    Join Date
    Jan 2009
    Posts
    26
    Thank you, it's clear now.

Popular pages Recent additions subscribe to a feed