Search code examples
c++chargarbage

cout corrupt char*


I have written a code to print the name of 2 workers, but instead it prints garbage.

cout << "highest salary: " << highestSalary.getID() << " " << highestSalary.getName() << endl;

cout << "hardest worker: " << mostHours.getID() << " " << mostHours.getName();

the function getName() is defined in the worker class as:

char* Worker::getName()
{
    char temp[20];

    int i;
    strcpy(temp, name);

    return temp;
}

going through this on the debugger I tried putting the value of highestSalary.getName() inside a ver char* temp, and the value was what i anticipated, let's say "bob", but after the cout the value was "" and the cout printed garbage.


Solution

  • You are passing a pointer to a local variable. Once your function ends, this variable is gone.

    If this is C++ you should use the string class. If for whatever reason you don't, at least be const correct:

    const char* Worker::getName() const 
    {
        return name;
    }