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

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


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

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

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

getMemory(str);

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

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

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

所以 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);
}

看输出结果


限时特惠:
本站持续每日更新海量各大内部创业课程,一年会员仅需要98元,全站资源免费下载
点击查看详情

站长微信:Jiucxh

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注