开发者

Passing a pointer address

int main()
{
  int x = 2, y = 4;
  func(&x, &y);
  printf("%d %d\n", x, y);
  return 0;
}

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

Hi

For this code i have no idea why the output is 2 4 instead of 4 4. Since x = y in func() means x now points to the address of y, and y = x in func() means y now points to the address of x开发者_开发百科 (which is y), both variables are now pointing to y already.

Many thanks!


The answer is simple: You change the pointer values inside func - but not the values they point at. I guess you'd like to swap the variables (due to the temp var).

This code should work (swapping values):

void func(int *x, int *y)
{
    int temp = *x; // dereferencing the pointer to get the value it points at.
    *x = *y;
    *y = temp;
}

Too keep your initial expectations (which don't make any sense code wise due to the second assignment):

void func(int *x, int *y)
{
    *x = *y;
    *y = *x;
}


Nope, func() will receive copies of those addresses and this won't affect the variables outside the function - all changes done to variables local to func() will be discarded once func() exits.


You are just temporarily assigning the address of 'x' to the address of 'y' within func. In order to make the assignment, you need to dereference your pointers.

*x = *y;
*y = *x;


Try this

#include <iostream>

using namespace std;

void func(int *x, int *y);

int main()
{
  int x = 2, y = 4;

  func(&x, &y);

  //printf("%d %d\n", x, y);

  cout << "X - " << x << endl;

  cout << "Y - " << y << endl;

  return 0;

}

void func(int *x, int *y)    
{
  int temp;

  temp = *x;
  *x = *y;
  *y = temp;

}


You're making copies of the passed in pointers, they are local to your function. Any change you make to them doesn't affect the outside. You should capture the pointers by reference &.

void func(int*& x, int*& y){
  // as before...
}

Now the changes inside the function will be correctly reflected outside of it. On problem remains though. You're passing in the address of local variables, and attempt to change their pointers - that doesn't work. When you take the address of a variable &x, you make a new temporary pointer, which can't be converted to a reference-to-pointer. Do this instead:

int main(){
  int x = 2, y = 4;
  int *px = &x, *py = &y;
  func(px, py);
  printf("%d %d\n",*px,*py);
}

Edit: If you instead want to swap / set the values of x and y and not just some pointers, do as the other answers state.


The problem is that you're trying to write your own version of std::swap. This will work:

  int x = 2, y = 4;
  std::swap(&x, &y);
  printf("%d %d\n", x, y);
  return 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜