Swapping pointers in C (char, int)

后端 未结 6 733
后悔当初
后悔当初 2020-11-29 15:46

I have been struggling to understand the different behaviour when swapping pointers in C. If I want to swap two int pointers, then I can do

void         


        
6条回答
  •  长情又很酷
    2020-11-29 16:32

    This example does not swap two int pointers. It swaps the value of the integers that pa and pb are pointing to. Here's an example of what's going on when you call this:

    void Swap1 (int *pa, int *pb){
        int temp = *pa;
        *pa = *pb;
        *pb = temp;
    }
    
    int main()
    {
        int a = 42;
        int b = 17;
    
    
        int *pa = &a;
        int *pb = &b;
    
        printf("--------Swap1---------\n");
        printf("a = %d\n b = %d\n", a, b);
        swap1(pa, pb);
        printf("a = %d\n = %d\n", a, a);
        printf("pb address =  %p\n", pa);
        printf("pa address =  %p\n", pb);
    }
    

    The output here is:

    a = 42
    b = 17
    pa address =  0x7fffdf933228
    pb address =  0x7fffdf93322c
    --------Swap---------
    pa = 17
    pb = 42
    a = 17
    b = 42
    pa address =  0x7fffdf933228
    pb address =  0x7fffdf93322c
    

    Note that the values swapped, but the pointer's addresses did not swap!

    In order to swap addresses we need to do this:

    void swap2 (int **pa, int **pb){
        int temp = *pa;
        *pa = *pb;
        *pb = temp;
    }
    

    and in main call the function like swap2(&pa, &pb);

    Now the addresses are swapped, as well as the values for the pointers. a and b have the same values that the are initialized with The integers a and b did not swap because it swap2 swaps the addresses being being pointed to by the pointers!:

    a = 42
    b = 17
    pa address =  0x7fffddaa9c98
    pb address =  0x7fffddaa9c9c
    --------Swap---------
    pa = 17
    pb = 42
    a = 42
    b = 17
    pa address =  0x7fffddaa9c9c
    pb address =  0x7fffddaa9c98
    

    Since Strings in C are char pointers, and you want to swap Strings, you are really swapping a char pointer. As in the examples with an int, you need a double pointer to swap addresses.

    The values of integers can be swapped even if the address isn't, but Strings are by definition a character pointer. You could swap one char with single pointers as the parameter, but a character pointer needs to be a double pointer in order to swap the strings.

提交回复
热议问题