v
oid GetMemory(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
}
|
void Test(void)
{
char *str = NULL;
GetMemory(str, 100);
// str 仍然爲 NULL
strcpy(str, "hello");
// 運行錯誤
}
|
void GetMemory2(char **p, int num)
{
*
p = (char *)malloc(sizeof(char) * num);
}
|
void Test2(void)
{
char *str = NULL;
GetMemory2(&str, 100);
// 注意參數是
&str
,而不是
str
strcpy(str, "hello");
cout<< str << endl;
free(str);
}
|
char *GetMemory3(int num)
{
char *p = (char *)malloc(sizeof(char) * num);
return p;
}
|
void Test3(void)
{
char *str = NULL;
str = GetMemory3(100);
strcpy(str, "hello");
cout<< str << endl;
free(str);
}
|
char *
GetString
(void)
{
char p[] = "hello world";
return p;
//
編譯器將提出警告
}
|
void Test4(void)
{
char *
str
=
NULL;
str
=
GetString
();
//
str
的內容是垃圾
cout<<
str
<< endl;
}
|
char *Get
String
2(void)
{
char *p = "hello world";
return p;
}
|
void Test5(void)
{
char *
str
= NULL;
str
=
Get
String
2();
cout<<
str
<< endl;
}
|