指针传参误区

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

#include 
#include 
#include 
#include 

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;
}

指针传参误区_第1张图片
形式2:采用二级指针的形式,func(**a,*b)

#include 
#include 
#include 
#include 

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;
}


指针传参误区_第2张图片
同样的若是要修改指针a的内容,如果a为空指针在函数内调用 *a=*b;就会造成段错误,

#include 
#include 
#include 
#include 

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;
}

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

你可能感兴趣的:(c指针)