函數形參是指針變量,直接對其賦值(指針相互賦值),只是改變了它的指向,原先傳入的指針指向的內容並沒改變;
若要想改動其指向的值,需要通過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