void getmemory(char p)
{
p=(char ) malloc(100);
strcpy(p,“hello world”);
}
int main( )
{
char *str=NULL;
getmemory(str);
printf(“%s/n”,str);
free(str);
return 0;
}會出現什麼問題?
【標準答案】程序崩潰,getmemory中的malloc 不能返回動態內存, free()對str操作很危險。
參考網上的代碼:
void getmemory(char *p)
{
p=(char ) malloc(100);
strcpy(p,“hello world”);
}
int main( )
{
char str=NULL;
getmemory(&str);
printf(“%s/n”,str);
free(str);
return 0;
}
個人註解:
char str=NULL;相當於定義一個字符串str,也是字符指針str。
getmemory(&str);傳的是字符串地址。
char *p可看成是 (char )p意爲字符串str的指針p。
p爲字符串str。亦是單字符的指針str。