C/C++指針作爲函數形參注意點

    函數形參是指針變量,直接對其賦值(指針相互賦值),只是改變了它的指向,原先傳入的指針指向的內容並沒改變

若要想改動其指向的值,需要通過memcpy或通過指針調用賦值;

 

示例:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <poll.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>

using namespace std;


int fun(int *c)
{

    int b=10;

    c=&b;
    // memcpy(c, &b, sizeof(int));//或 *c = b;


    printf(">> : in fun , c = %d \r\n", *c);
    return 0;
}

int main()
{
    int *A;
    *A = 1;

    int a = 1;
    fun(&a);
    fun(A);
    printf(">> : a = %d \r\n", a);
    printf(">> : A = %d \r\n", *A);

    return 0;
}

以上代碼輸出:a和A的值未改變

d_underdrive_pc/src$ ./pointer_test.o 
>> : in fun , c = 10 
>> : in fun , c = 10 
>> : a = 1 
>> : A = 1 

代碼更改如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <poll.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>

using namespace std;


int fun(int *c)
{

    int b=10;

    //c=&b;
    memcpy(c, &b, sizeof(int));//或 *c = b;


    printf(">> : in fun , c = %d \r\n", *c);
    return 0;
}

int main()
{
    int *A;
    *A = 1;

    int a = 1;
    fun(&a);
    fun(A);
    printf(">> : a = %d \r\n", a);
    printf(">> : A = %d \r\n", *A);

    return 0;
}

 以上代碼輸出:a和A的值改變

>> : in fun , c = 10 
>> : in fun , c = 10 
>> : a = 10 
>> : A = 10

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章