void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
这里在调用函数GetMemory时只是给局部半量p分配了存储空间,而不是给str分配空间.所以运行会出错.
如果要改,代码如下:
void GetMeMory(char **p)
{
*p = (char *)malloc(100);
}
void Test()
{
char *str = NULL;
GetMeMory(&str);
strcpy(str, "hello world");
printf(str);
}
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
这里在调用函数GetMemory时只是给局部半量p分配了存储空间,而不是给str分配空间.所以运行会出错.
如果要改,代码如下:
void GetMeMory(char **p)
{
*p = (char *)malloc(100);
}
void Test()
{
char *str = NULL;
GetMeMory(&str);
strcpy(str, "hello world");
printf(str);
}