Pointer/Variable

This is a discussion on Pointer/Variable within the C++ Programming forums, part of the General Programming Boards category; Code: int *x, y; x = y; Why does that give an error?...

  1. #1
    Air
    Air is offline
    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,801
    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 02:22 PM.

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

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21