pointers...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kpdp
    New Member
    • Nov 2008
    • 7

    pointers...

    Hey.
    Can anyone tell me why we need pointers when swapping varibles such as:
    void swap (int *x, int *y)
    {
    int temp;
    temp = *x;
    *x =*y;
    *y = temp;
    }

    int x=12, y=4
    swap (&x,&y);

    why would they swap values, as opposed to using...

    void swap (int x, int y)
    {
    int temp;
    temp = x;
    x =y;
    y = temp;
    }

    ...where the x and y value won't swap?
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    Because: swap(a,b) doesn't mean use the variables a and b directly in the function swap.

    The variables values are copied over to the variables in the function argument. swap(int x, int y) has its own x and y. So you'll swap the two variables in the function, but it won't change anything else. If you use pointers, you'll get a copy of the pointers yes. But you can then change the pointed to values.

    Comment

    • kpdp
      New Member
      • Nov 2008
      • 7

      #3
      ohhhhh,,,,okay! that makes sense. thx!

      Comment

      Working...