小妹最近去面试,常常遇到下面几个程序,我面试回来运行了一下这些程序,可是还是不能明白运行结果怎么是那样的,望各位大虾指点迷津。
问题:写出运行test函数程序运行的结果
1.
void GetMemory(char *p)
{ p=(char *)malloc(100);
}
void Test(void)
{
char *str=NULL;
GetMemory(str);
strcpy(str,"hello world");
printf("%sn",str);
}
linux下用gcc编译,运行,segment fault.(经过试验发现段错误发生在引用str处)
2.
char* GetMemory(void)
{ p[]="hello world";
return p;
}
void Test(void)
{
char *str=NULL;
str=GetMemory();
printf("%sn",str);
}
运行后发现现实的都是乱码,编译时显示:in function 'GetMemory', warning:function returns address of local variable
3.
void GetMemory(char **p,int num)
{
*p=(char *)malloc(num);
}
void Test(void)
{
char *str=NULL;
GetMemory(&str,100);
strcpy(str,"hello");
printf("%sn",str);
}
这个没什么错误,运行,输出“hello”
4.
void Test(void)
{
char *str=(char *)malloc(100);
strcpy(str,"hello");
free(str);
if(str!=NULL)
{
strcpy(str,"world");
printf("%sn",str);
}
}
这个不知道为什么,留着free那句指令和注释掉它,程序都显示“world”
请好心人帮忙解答一下,因为这个问题我已经遇到好几次了,几乎每次笔试都考,实在郁闷!!
|
了解一下传值和传址方式的原理。