为什么仅在添加cout线后输出无法显示变量的内容?

I'm*_*gon 1 c++

#include <iostream>

using namespace std;

class Marks
{
public:
    char* name();
};

char* Marks::name()
{
    char temp[30];
    cout<<"Enter a name:"<<endl;
    cin.getline(temp,30);
    return temp;
}

int main ()
{
    char *name;
    Marks test1;
    name=test1.name();

    //cout<<"name:"; //uncomment this line to see the problem
    cout<<name<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

dir*_*tly 8

您正在返回本地变量的地址:

char temp[30];
// ...
return temp;
Run Code Online (Sandbox Code Playgroud)

这是C或C++中的严格禁忌.你从Marks::name()你的temp变量出来的那一刻就是BOOM!您无法再访问它 - 这样做会调用未定义的行为.试试这个,

#include <string> // somewhere at the top
// ...
std::string Marks::name()
{
   std::string line;
   cout<<"Enter a name:"<<endl;
   std::getline(cout, line);
   return line;
}
Run Code Online (Sandbox Code Playgroud)


And*_*ndy 5

问题是因为名称指向的值已被破坏.您正在返回本地变量的地址Marks::name().最有可能是第一个的副作用cout是导致内容name被破坏.当第一个cout被注释掉时,你可能只是幸运.

执行此操作的正确方法是分配一些内存,返回该内存,然后在完成后将其销毁:

char* Marks::name()
{
    char* temp = new char[30];
    cout<<"Enter a name:"<<endl;
    cin.getline(temp,30);
    return temp;
}

int main ()
{
    char *name;
    Marks test1;
    name=test1.name();

    cout<<"name:";
    cout<<name<<endl;

    delete[] name;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

不要忘记使用delete[],而不仅仅是delete,因为否则只会释放第一个字符.