这道题为什么错了?请说明原因

flydream0
博客专家认证
2010-12-08 09:19:56

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char *p)
{
p=(char *) malloc(100);
}
int main( )
{
char *str=NULL;
getmemory(str);
strcpy(str,"hello world");
printf("%s/n",str);
free(str);
return 0;
}

大家请看看,为什么这道题错了?编译通过,但是运行时程序会崩,请说明原因,我想知道根本性上的原因.
...全文
101 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
flydream0 2010-12-08
  • 打赏
  • 举报
回复
3Q!开窍了
就想叫yoko 2010-12-08
  • 打赏
  • 举报
回复
++,真是个论坛常见的问题[Quote=引用 1 楼 dubiousway 的回复:]
oid getmemory(char **p)
{
*p=(char *) malloc(100);
}
int main( )
{
char *str=NULL;
getmemory(&str);//要通过一个函数改变一个变量的值,你要传递这个变量的地址给函数,不管它什么类型
[/Quote]
Athenacle_ 2010-12-08
  • 打赏
  • 举报
回复

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char **p)
{
*p=(char *) malloc(100);
}
int main( )
{
char *str=NULL;
getmemory(&str);
strcpy(str,"hello world");
printf("%s/n",str);
free(str);
return 0;
}
「已注销」 2010-12-08
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char **p)
{
*p=(char *) malloc(100);
}
int main( )
{
char *str=NULL;
getmemory(&str);
strcpy(str,"hello world");
printf("%s/n",str);
free(str);
return 0;
}


你传的是指针变量的地址,不是str的地址
dubiousway 2010-12-08
  • 打赏
  • 举报
回复
oid getmemory(char **p)
{
*p=(char *) malloc(100);
}
int main( )
{
char *str=NULL;
getmemory(&str);//要通过一个函数改变一个变量的值,你要传递这个变量的地址给函数,不管它什么类型

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧