傳參問題


#include <stdio.h>

#include <stdlib.h>

void getmemory(char *p) //函數的參數是局部變量,在這里給它分配內存還在,但是P釋放了。

{

p=(char *) malloc(100);

}

int main( )

{

char *str=NULL;

getmemory(str);

strcpy(str,"hello world");

printf("%s/n",str);

free(str);

return 0;

}

答: 程序崩潰,getmemory中的malloc 不能返回動態內存, free()對str操作很危險

 

修改后的程序如下:

#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;
}
*/

//傳地址的地址
/*
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;
}
*/

char * getmemory()
{
//char*p=(char *) malloc(100);
 static char p[100];
 return p;

}
int main( )
{
char *str=NULL;
str=getmemory();
strcpy(str,"hello world");
printf("%s\n",str);
//free(str);
return 0;
}


 運行結果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM