小编Fyx*_*yxe的帖子

什么决定在返回时解除分配本地分配?

所以,我有两段代码,一段有效,另一段没有.第一部分只是一个测试,以确定char指针在从本地分配返回后是否仍然有效.出于某种原因,这有效:

    char* test(){
        char* rawr="what";
        return rawr;  
    }
Run Code Online (Sandbox Code Playgroud)

但是这个不起作用:

    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;  
    }
Run Code Online (Sandbox Code Playgroud)

我敢打赌,有一种更好的方法来完成从完整路径中删除文件名的任务,但是现在我只想弄清楚为什么这个char指针被删除而另一个没有删除.如果我不得不猜测我会说它因为我宣布它不同,或者因为它更大.是的,我可以传递另一个char指针作为此函数的参数,但这不会回答我的问题.

c++ variables scope memory-management

0
推荐指数
1
解决办法
212
查看次数

标签 统计

c++ ×1

memory-management ×1

scope ×1

variables ×1