Question

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.

Was it helpful?

Solution 2

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;
}

OTHER TIPS

NO NO NO, you are returning a pointer to a local function variable. That's why it crashes.

Do this instead:

std::string Worker::getName()
{
   std::string temp(name); // not sure what type of name is...
   return temp;
}

Don't forget to #include<string>.

Now you have real C++, not C and pointers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top