Swapping pointers in C (char, int)

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

    If you have the luxury of working in C++, use this:

    template
    void swapPrimitives(T& a, T& b)
    {
        T c = a;
        a = b;
        b = c;
    }
    

    Granted, in the case of char*, it would only swap the pointers themselves, not the data they point to, but in most cases, that is OK, right?

提交回复
热议问题