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 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 **** ! 
段错误 (核心已转储)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值