指针传参误区

C语言中指针作为形参传递时,func(*a, *b) 这种形式的话,是无法通过简单的 a=b来修改的,在函数体内a的地址确实被修改成b的地址了,但是当函数执行结束时,a的地址会重新回到原本的地址里面,这边是由于函数执行结束,函数的栈地址被释放了,若是要获取a修改的地址可以采用一下两种形式获取:
形式1:return addr;

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <malloc.h>

static int * test(int*a,int*b)
{
    a = b;
    return a;
}
int main(int argc, char *argv[])
{
    int *a = NULL;
    int te = 10;
    int *b = &te;
    a = test(a,b);
    printf("a=%d",*a);
    return 0;
}

在这里插入图片描述
形式2:采用二级指针的形式,func(**a,*b)

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <malloc.h>

static void test(int**a,int*b)
{
    *a = b;
}
int main(int argc, char *argv[])
{
    int *a = NULL;
    int te = 12;
    int *b = &te;
    test(&a,b);//传入一级指针a的地址
    printf("a=%d",*a);
    return 0;
}


在这里插入图片描述
同样的若是要修改指针a的内容,如果a为空指针在函数内调用 *a=*b;就会造成段错误,

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <malloc.h>

static void test(int*a,int*b)
{
    *a = *b;
}
int main(int argc, char *argv[])
{
    int *a = NULL;
    int te = 12;
    int *b = &te;
    test(a,b);
    printf("a=%d",*a);
    return 0;
}

在这里插入图片描述
野指针不会有这个问题,因为野指针会被随机的分配一块内存空间,但是实际使用中仍不建议这样使用,使用野指针操作,可能会踩到其他内存空间造成莫名其妙的死机,并且很难排插问题。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值