请帮我解决二道简单的送分题,每题30分,急,帮帮忙好吗

arnoldmjw 2003-06-27 10:05:06
以下的两个程序有没有错误,若没有请写出输出的结果,若有则指出来并改正。

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

char* GetMemory();
void test();

int main()
{
test();
return 0;
}

void test()
{
char *str=NULL;
str=GetMemory();
printf("%s",str);
}
char *GetMemory()
{
char p[]="hello";
return(p);
}

...全文
49 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Inkick 2003-06-27
  • 打赏
  • 举报
回复
嗯,第一个有错误
把char[]改为char*就可以了
arnoldmjw27 2003-06-27
  • 打赏
  • 举报
回复
现在有事出去一下,一定会给分的,谢谢你的帮助。ok
arnoldmjw27 2003-06-27
  • 打赏
  • 举报
回复
12点以后再给分
zteliubin 2003-06-27
  • 打赏
  • 举报
回复
很简单但是也很基本的问题哟!

给分吧!
zteliubin 2003-06-27
  • 打赏
  • 举报
回复
2.错误,c语言传值不传地址,因此,GetMemory()申请的内存不能返回
应该是:
char* GetMemory()
{
char *p=(char*)malloc(100);
return p;
}


void test()
{
char *str=NULL;

str = GetMemory();
if(str == NULL)
return;
strcpy(str,"hello");
printf("%s",str);
free(str);
}


zteliubin 2003-06-27
  • 打赏
  • 举报
回复
1: 有错误!

char *GetMemory()
{
char p[]="hello";
return(p);
}
中分配的内存在栈上,函数返回后,栈释放,应该使用: 
p = malloc();
arnoldmjw 2003-06-27
  • 打赏
  • 举报
回复
第二题
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

void GetMemory(char*);
void test();

int main()
{
test();
return 0;
}

void test()
{
char *str=NULL;

GetMemory(str);
strcpy(str,"hello");
printf("%s",str);
}
void GetMemory(char *p)
{
p=(char*)malloc(100);
}

69,371

社区成员

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

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