所以,我有2个代码,一个有效,另一个没有。第一部分只是一个测试,以确定char指针在从本地分配返回后是否仍然有效。出于某种原因,这有效:
char* test(){
char* rawr="what";
return rawr;
}
但是这个不起作用:
char* folderfromfile(char* filz) //gets the folder path from the file path
{
//declarations
int lastslash=-1;
int i =0;
char rett[256];
for(i;(int)filz[i]!=0;i++)
if(filz[i]=='\\')
lastslash=i; //records the last known backslash
if(lastslash==-1)
return ""; //didn't find a backslash
for(i=0;i<=lastslash;i++)
rett[i]=filz[i]; // copies to new string
rett[i] =0; //end of string
cout << &rett << "====" << rett << endl;
system("pause>nul");//pause so i can watch over the memory before it deallocates
return rett;
}
我敢打赌,有一种更好的方法可以完成从完整路径中删除文件名的任务,但是现在我只想弄清楚为什么这个char指针被删除而另一个没有删除。如果我不得不猜测我会说它因为我宣布它不同,或者因为它更大。是的,我可以传递另一个char指针作为此函数的参数,但这不会回答我的问题。
答案 0 :(得分:5)
rett在堆栈上分配,因此当方法返回时,它的内存空间不再有效。
rawr指向程序运行时编译器可能保留在(只读)内存中的文字。
这两种方法都是错误的。
您需要使用new(或C中的malloc)分配缓冲区或使用std :: string。
答案 1 :(得分:0)
char* test(){
char* rawr="what";
return rawr;
}
字符串文字"what"
不在堆栈上分配 - 它在程序的整个生命周期内保持有效。但是不能修改它。指针rawr
本身位于堆栈中,但如果您编写&rawr
之类的内容,获取指向指针的指针,则这只是一个问题。
char* folderfromfile(char* filz){ //gets the folder path from the file path
int lastslash=-1,i=0;char rett[256]; //declarations
///// ...
return rett;
}
然而,这会在堆栈上放置数组。 rett
这里隐式&rett[0]
,也就是说,得到一个指向数组第一个元素的指针,它在堆栈中非常多,并且在返回后无效。