c++ pointer swap problem

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

It's a basic question I created a function that swaps pointer addresses with each other, but when I print it out, it becomes the original value. Debugging doesn't solve the question!

#include <iostream>
using namespace std;

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

int main(int argc, const char * argv[]) {

    int num1=20, num2=30;
    swap(&num1, &num2);
    cout<<num1<<"  "<<num2<<endl;

    return 0;

The desired result is 3020.

The real result is 2030.


2022-09-20 11:33

1 Answers

Swap function is created incorrectly. The code in the question creates an int-type pointer variable, which is a local variable called a and b, and then replaces the address values stored in the two pointer variables, a and b, within the function.

What you actually have to do is change the values that are stored in the memory for each address through the address value that is given initially. You need to use the *speaker to access memory. Please refer to the code below.

#include <iostream>
using namespace std;

void my_swap(int* a, int* b)
    int temp = *a;
    *a = *b;
    *b = temp;

int main()
    int num1 = 20, num2 = 30;
    my_swap(&num1, &num2);
    cout << num1 << "  " << num2 << '\n';

2022-09-20 11:33

If you have any answers or tips

© 2022 pinfo. All rights reserved.