C语言中一个内存的思考题
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
请问运行Test函数会有什么样的结果?或者还是会出错?什么原因?
[解决办法]
传参进去
- C/C++ code
char *GetMemory(char **p){ *p = (char *)malloc(6); strcpy(*p, "hello"); return *p;}int main(int, char **){ char *str = NULL; str = GetMemory(&str); printf(str); return 0;}
[解决办法]
结果不确定,如果按1楼说的用char*就没问题,因为是"hello world"是常量
[解决办法]
支持1楼的,但是1楼叛变了...
char p[] = "hello" 申请了一个数据保存"hello" ,是存放在栈中的,函数返回就消亡了.
和 char *p = "hello" "hello"是申请在全局区的, p 这个指针变量是申请在栈中的.
具体看一下下面的2个例子:
- C/C++ code
#include <stdio.h>char *GetMemory(void){ char p[] = "hello world"; return p;}void main(void){ char *str = NULL; str = GetMemory(); printf("%s\n", str);}