c语言字符串函数_C语言,字符串指针做函数参数

看一下下面这段代码有什么问题?

#include "stdio.h"
//#include "stdbool.h"
#include "string.h"
#include "stdlib.h"
#include "math.h"

void getMemory(char *p)
{
	/*char *p = str*/
	p = (char *)malloc(100);
	strcpy(p,"hello world");
	printf("p:%sn",p);
}

int main()
{
	printf("Enter main...n");
	char *str = NULL;
	printf("str:%pn",str);
	getMemory(str);
	
	printf("%sn",str);
	
	if(str != NULL)
		free(str);
	
    return (0);
}

我们直接看输出,输出是这样的

1fe67e396db2c2738d1b0986c439b375.png

分析一下 很多人对函数传参数还不是特别清楚

void getMemory(char *p)
{
	/*char *p = str*/
	p = (char *)malloc(100);
	strcpy(p,"hello world");
	printf("p:%sn",p);
}

getMemory(str);

str 是一个指针变量,也就是说 它存的是一个内存地址,这个内存地址指向类型是 char * 「也就是字符串」

但是把str 传给getMemory(char * p)的时候,它传递的是 str 的副本,不是它本身

既然传的是副本,在getMemory 里面操作的代码,也都是对这个副本进行操作,函数调用结束,也就销魂回收了。

所以 str 还是原来的 NULL

如何修改?

#include "stdio.h"
//#include "stdbool.h"
#include "string.h"
#include "stdlib.h"
#include "math.h"

void getMemory(char **p)
{
	/*char **p = &str*/
	*p = (char *)malloc(100);
	strcpy(*p,"hello world");
	printf("p:%sn",*p);
}

int main()
{
	printf("Enter main...n");
	char *str = NULL;
	printf("str:%pn",str);
	getMemory(&str);
	
	printf("%sn",str);
	
	if(str != NULL)
		free(str);
	
    return (0);
}

看输出结果

696728ee8dfde565bfe4f4cab3ca30a6.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值