C/C++ 内存传递 指针
2015-12-19 17:41
357 查看
程序1:
[cpp] view
plaincopy
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就正确了
[cpp] view
plaincopy
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的地址,形参改为指向指针的指针
[cpp] view
plaincopy
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();
}
[cpp] view
plaincopy
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就正确了
[cpp] view
plaincopy
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的地址,形参改为指向指针的指针
[cpp] view
plaincopy
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();
}
相关文章推荐
- C++中的“error:LNK2005 已经在*.obj中定义”异常问题
- 值得推荐的C/C++框架和库
- C++之学后感
- C++总的const使用说明
- 【LeetCode从零单刷】Bulb Switcher
- C语言编写静态链接库及其使用
- C语言实现标准正态分布函数和0-1均匀分布函数
- C语言实现常见的矩阵运算函数
- 黑马程序员-OC语言-关键字self与super
- C语言qsort库函数使用说明
- C语言运算符的优先级和结合性
- c++如何将一块内存拆分成两块内存
- C++ 红黑树增加、删除等操作
- C++ 贪心算法部分背包问题
- 黑马程序员-OC语言-多态
- C++如何将两块内存的数据合并到一块内存
- 安卓JNI调试、C++/C代码调试、native层调试策略
- 任务调度问题
- 黑马程序员-OC语言-继承
- Treap堆的插入,删除操作