Swapping pointers in C (char, int)

后端 未结 6 727
后悔当初
后悔当初 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

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

    You need to know the following -

    int a = 5; // an integer, contains value
    int *p; // an integer pointer, contains address
    p = &a; // &a means address of a
    a = *p; // *p means value stored in that address, here 5
    

    void charSwap(char* a, char* b){
        char temp = *a;
        *a = *b;
        *b = temp;
    }
    

    So, when you swap like this. Only the value will be swapped. So, for a char* only their first char will swap.

    Now, if you understand char* (string) clearly, then you should know that, you only need to exchange the pointer. It'll be easier to understand if you think it as an array instead of string.

    void stringSwap(char** a, char** b){
        char *temp = *a;
        *a = *b;
        *b = temp;
    }
    

    So, here you are passing double pointer because starting of an array itself is a pointer.

提交回复
热议问题