C语言,字符串指针做函数参数
发布日期:2021-06-30 18:43:44
浏览次数:3
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
表示我来过!
[***.240.166.169]2024年04月30日 13时27分19秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Oracle 作业记录
2019-04-30
putty连接AWS配置(multimedia project)
2019-04-30
Hourglass Network 沙漏网络 (pose estimation姿态估计)
2019-04-30
OpenCV实战(二)——答题卡识别判卷
2019-04-30
目标检测神经网络的发展历程(52 个目标检测模型)
2019-04-30
Boundary loss 损失函数
2019-04-30
tensorflow使用tensorboard进行可视化
2019-04-30
凸优化 convex optimization
2019-04-30
数据库索引 & 为什么要对数据库建立索引 / 数据库建立索引为什么会加快查询速度
2019-04-30
IEEE与APA引用格式
2019-04-30
research gap
2019-04-30
pytorch训练cifar10数据集查看各个种类图片的准确率
2019-04-30
Python鼠标点击图片,获取点击点的像素坐标
2019-04-30
路径规划(一) —— 环境描述(Grid Map & Feature Map) & 全局路径规划(最优路径规划(Dijkstra&A*star) & 概率路径规划(PRM&RRT))
2019-04-30
RRT算法(快速拓展随机树)的Python实现
2019-04-30