函数形参是指针变量,直接对其赋值(指针相互赋值),只是改变了它的指向,原先传入的指针指向的内容并没改变;
若要想改动其指向的值,需要通过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 d =1;
int *A;
A = &d;
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
指针变量, 在访问其指向对象之前,需要先给其指定对象(分配内存空间),否者会出现“”段错误 (核心已转储)“”:
printf("**** 0000 **** ! \r\n");
float* A;
*A = 1; //错误,此时A未指向任何内存空间
printf("****111**** ! \r\n");
输出:
**** 0000 **** !
段错误 (核心已转储)