使用指针形参分配内存的问题

本文探讨了C语言中通过一级指针和二级指针在函数中进行内存分配和管理的差异。示例代码展示了如何在函数内部通过一级指针分配内存,但该内存仅在函数内部有效,而通过二级指针则能在函数外部影响原始指针的值,实现内存的跨函数管理。理解这一点对于避免内存泄漏和正确使用指针至关重要。
摘要由CSDN通过智能技术生成

1、通过形参传递一级指针:只在函数内部生效,实际并没有改变指针的指向

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void test(char *p){
	printf("p1 = %p\n",p);
	p = malloc(20);
	printf("p2 = %p\n",p);
	strcpy(p,"hello world");
	printf("p3 = %s\n",p);
	
}

int main(){	
	char * p = NULL;
	test(p);
	printf("p = %p\n",p);
	//free(p);
    return 0;
}

运行结果:

 2、通过形参传递二级指针,在函数内部申请的空间可以在调用位置生效

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void test(char **p){
	printf("p1 = %p\n",p);//一级指针的地址(&pc)
	printf("p2 = %p\n",*p);//一级指针里面的值:NULL
	*p = malloc(20);
	printf("p3 = %p\n",*p);
	strcpy(*p,"hello world");
	printf("p4 = %s\n",*p);
	
}

int main(){
	
	char * pc = NULL;
	printf("pc1 = %p\n",&pc);
	test(&pc);
	
	printf("pc2 = %p\n",pc);
	printf("pc3 = %s\n",pc);
	
	free(pc);
    return 0;
}

运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑三少_Creat

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值