看一下下面这段代码有什么问题?
#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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。