C语言面试题
下面的程序有什么问题?
void GetMemory( char *p )
{
p = (char *) malloc( 100 );
}
void Test( void )
{
char *str = NULL;
GetMemory( str );
strcpy( str, "hello world" );
printf( “%s”,str );
}
这个一个考验对指针理解的题目,上面程序在运行之后:
1、调用GetMemory( str )后, str并未产生变化,依然是NULL.只是改变的str的一个拷贝的内存的变化
2、strcpy( str, "hello world" );程序运行到这将产生错误。
改正有2种方法:
1、二级指针推荐使用
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(sizeof(char) * num);
}
void Test(void)
{
char *str=NULL;
GetMemory=(&str);
strcpy(str,"hello world");
printf(str);
free(str);
str=NULL;
}
2、
char *GetMemory()
{
char *p=(char *)malloc(100);
return p;
}
void Test(void){
char *str=NULL;
str=GetMemory();
strcpy(str,"hello world");
printf(str);
free(str);
str=NULL;
}
再看看下面的一段程序有什么错误:
swap( int* p1,int* p2 )
{
int *p;
*p = *p1;
*p1 = *p2;
*p2 = *p;
}
在swap函数中,p是一个“野”指针,有可能指向系统区,导致程序运行的崩溃。
应该改为:
swap(int* p1, int* p2)
{
int tmp;
tmp=*p1;
*p1=*p2;
*p2=tmp;
}
浙公网安备 33010602011771号