7.4指针参数是如何传递内存的?
void 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 *GetString2(void)
{
char *p = "hello world";
return p;
} |
void Test5(void)
{
char *str = NULL;
str = GetString2();
cout<< str << endl;
} |