-34- C to achieve zero-based video switching function value by two pointer variables

Review: The value of the transfer function

Because during the function call, the arguments passed to the parameter value is, therefore, parameter change, can not affect the argument:

#include <stdio.h>

void FakeSwap(int nArg1, int nArg2)
{
    int nTemp = nArg1;
    nArg1 = nArg2;
    nArg2 = nTemp;
}

int main(int argc, char* argv[])
{
    int nValue1 = 100;
    int nValue2 = 200;
    printf("交换前:%d, %d\r\n", nValue1, nValue2);
    FakeSwap(nValue1, nValue2);
    printf("交换后:%d, %d\r\n", nValue1, nValue2);
    return 0;
}

Above, parameter changes can not affect the arguments of the function call could not be completed nValue1, nValue2 exchange.

Using the pointer values ​​of two variables exchange

#include <stdio.h>

void PointerSwap(int* pArg1, int* pArg2)
{
    int nTemp = *pArg1;
    *pArg1 = *pArg2;
    *pArg2 = nTemp;
}

int main(int argc, char* argv[])
{
    int nValue1 = 100;
    int nValue2 = 200;
    printf("交换前:%d, %d\r\n", nValue1, nValue2);
    PointerSwap(&nValue1, &nValue2);
    printf("交换后:%d, %d\r\n", nValue1, nValue2);
    return 0;
}

Use of pointers, during the function call is still passed by value , however, the pointer reference operator by solving, according to the incoming address, the address of the modified value, to achieve the purpose of the exchange.
In practice, often by this method, without the return value, only the function pointer out from the information .

Guess you like

Origin www.cnblogs.com/shellmad/p/11695615.html
Recommended