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:%s\n",p);
}

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


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

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

void getMemory(char *p)
{
	/*char *p = str*/
	p = (char *)malloc(100);
	strcpy(p,"hello world");
	printf("p:%s\n",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:%s\n",*p);
}

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

看输出结果


扫码或长按关注

回复「 篮球的大肚子」进入技术群聊

发布了395 篇原创文章 · 获赞 788 · 访问量 72万+

猜你喜欢

转载自blog.csdn.net/weiqifa0/article/details/103740314