Swapping addresses of pointers in C++

后端 未结 5 2079
温柔的废话
温柔的废话 2021-01-01 02:38

How can one swap pointer addresses within a function with a signature?

Let\'s say:

int weight, height;
void swap(int* a, int* b);

S

5条回答
  •  灰色年华
    2021-01-01 03:09

    The new answer (since the question has been reformulated)

    is that addressed of variables are determined at compile time and can therefore not be swapped. Pointers to variables however can be swapped.

    Old answer: this was the answer when the question still implied swapping the values of 2 variables by means of a function:

    function call:

     int width=10, height=20;
     swap(&width, &height)
    

    implementation:

     void swap(int *a, int *b)
     {
          int temp;
          temp=*a;
          *a = *b;
          *b = temp;
     }
    

    or...without using a temporary variable: ;^)

     void swap(int *a, int *b)
     {
          *a ^= *b;
          *b ^= *a;
          *a ^= *b;
     }
    

    do watch out that the last method breaks for the case: swap (&a, &a). Very sharply pointed out by user9876 in the comments.

提交回复
热议问题