C/C++ 内存传递 指针
来源:互联网 发布:安卓ssr软件 编辑:程序博客网 时间:2024/06/04 21:22
程序1:
- void getmemory(char *p)
- {
- p=(char*)malloc(100);
- }
- void test(void)
- {
- char * str = NULL;
- getmemory(str);
- strcpy(str,"hello,world");
- printf(str);
- }
- int main()
- {
- test();
- }
程序1运行是会报错的,调用getmemory(str)后,在test函数内的局部变量str并未产生变化, strcpy ( str ,” hello , world ”) 写越界,造成segmentation fault。
要修改以上程序有两个办法,
修改1: 形参由char *p改成char *&p就正确了
- void getmemory(char *&p)
- {
- p=(char*)malloc(100);
- }
- void test(void)
- {
- char * str = NULL;
- getmemory(str);
- strcpy(str,"hello,world");
- printf(str);
- }
- int main()
- {
- test();
- }
修改2:传入str的地址,形参改为指向指针的指针
- void getmemory(char **p)
- {
- *p=(char*)malloc(100);
- }
- void test(void)
- {
- char * str = NULL;
- getmemory(&str);
- strcpy(str,"hello,world");
- printf(str);
- }
- int main()
- {
- test();
- }
0 0
- C/C++ 内存传递 指针
- C/C++ 内存传递 指针
- c内存管理--指针如何传递内存?
- C语言指针传递和内存分配
- C语言指针传递和内存分配
- C语言指针传递和内存分配
- C语言指针传递和内存分配
- c/c++指针参数如何传递内存
- C语言指针的指针传递内存的理解
- C指针参数传递
- 高质量c++(指针参数是如何传递内存的?)
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- 【杭电】[1001]Sum Problem
- VBA实现数组Array与集合Collection互换
- Codevs_P3372 选学霸(并查集+DP+背包)
- Gradle Buildscript
- ios客户端学习-日历控件
- C/C++ 内存传递 指针
- 向韦东山学:spi协议+oled裸板程序
- 分享个人maven本地库
- Java实现倒计时代码
- C/C++ 常量指针,指针常量
- Matlab借助匿名函数求隐函数
- Git常用命令
- Java中Properties文件值的获取
- 【杭电】[2006]求奇数的乘积