Question

Sorry but I thought I understood this with stack and heap by now but obviously I am wrong. I declared every object on the heap but all the same when the first metod is done I can see via std::cout that the time is ZERO, that is:

startTPtr: 00:00:00

When the time is printed within the function its ok but somehow it becomes destroyed after the functions ends.

Did I miss something crucial here? Should I return the pointer from the function?

Thanks in advance!!!

int main() {

   Clock *_clockPtr = new Clock();

   MyTime *_startTPtr = new MyTime();
   MyTime *_endTPtr = new MyTime();

   char *ch = new char[100];

   start_app(_startTPtr, _endTPtr, _clockPtr, ch);

   cout << "startTPtr: " << *_startTPtr << endl;

return 0;
}

void start_app(MyTime *_startTPtr, MyTime *_endTPtr, Clock *clock, char *ch) {

   cout << "Press ENTER to start and finish!";
   int newLine = 0;
   for (std::string line; std::getline(std::cin, line); ) {

    if (newLine == 0) {
        std::cout << "... ";
        MyTime* myTime1 = new MyTime(clock->give_me_the_time()); 
        _startTPtr = myTime1;
        cin >> ch;
    } else {
        MyTime* myTime2 = new MyTime(clock->give_me_the_time()); 
        _endTPtr = myTime2;
        break;
    }
    cout << "startTPtr: " << *_startTPtr << endl;
    newLine++;
}
}
Était-ce utile?

La solution

If you want to change an argument in a function and have it reflected in the caller of the function, you need to pass the argument by reference. Otherwise the arguments are copied and you only change the copies.

In your start_app function you want to change both _startTPtr and _endTPtr so you need to pass them as references to pointers to MyTime:

void start_app(MyTime *&_startTPtr, MyTime *&_endTPtr, Clock *clock, char *ch) { ... }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top