指针传参误区

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

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

相关推荐

  1. Python——

    2024-01-09 03:50:01       39 阅读
  2. 【Vue】组件

    2024-01-09 03:50:01       36 阅读
  3. 003

    2024-01-09 03:50:01       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-09 03:50:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-09 03:50:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-09 03:50:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-09 03:50:01       20 阅读

热门阅读

  1. 器件转行验证,秋招offer25-50w上岸!

    2024-01-09 03:50:01       36 阅读
  2. 1688商品详情API:实现商品详情自动化的关键步骤

    2024-01-09 03:50:01       42 阅读
  3. 常见服务/协议默认端口号、HTTP状态码

    2024-01-09 03:50:01       41 阅读
  4. 索引失效的情况

    2024-01-09 03:50:01       34 阅读
  5. 如何解决大模型的「幻觉」问题?

    2024-01-09 03:50:01       33 阅读
  6. 借名买房合同的效力

    2024-01-09 03:50:01       36 阅读