C语言,字符串指针做函数参数
发布日期:2021-06-30 18:43:44
浏览次数:4
分类:技术文章
本文共 1154 字,大约阅读时间需要 3 分钟。
看一下下面这段代码有什么问题?
#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);}
看输出结果
扫码或长按关注
回复「 篮球的大肚子」进入技术群聊
转载地址:https://linus.blog.csdn.net/article/details/103740314 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年05月01日 01时22分57秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
CodeForces - 996D Suit and Tie (暴力)
2019-04-30
ACM 2017 香港区域赛 E - Base Station Sites(二分)
2019-04-30
ACM 2018 青岛区域赛 J-Books (模拟)
2019-04-30
ACM 2016 沈阳区域赛 E - Counting Cliques (dfs)
2019-04-30
ACM 2017 北京区域赛 J-Pangu and Stones(区间dp)
2019-04-30
HDU - 5643 King's Game (约瑟夫环变式)
2019-04-30
UVA - 1452 Jump (约瑟夫环变式)
2019-04-30
POJ - 3517 And Then There Was One (约瑟夫环变式)
2019-04-30
HDU - 2068 RPG的错排 (错排+组合数)
2019-04-30
CodeForces 591C Median Smoothing(思维 模拟)
2019-04-30
升级yosemite后java出错的解决
2019-04-30