函数调用后指针发生变化

时间:2018-05-04 03:57:27

标签: c++ pointers

我有一个函数可以将对象添加到对象Process的向量中。 我有一个名为Process * CPU的私人成员,我的目标是让它指向我添加到向量的第一个进程。我可以继续添加更多进程,但CPU仍应指向第一个进程。

void DiskSched::addProcess() {    
      if (isEmpty()) {
         // If CPU is empty, the new process will automatically go to the CPU
         Process newProcess;
         newProcess.setProcessProperties(0,Header::PID,++Header::TIME);
         CPU = &newProcess; // assigning the first process to the CPU

         cout << endl;
         cout << "Process object: " << newProcess.getPageNum() << " "<< newProcess.getPID() << " " << newProcess.getTimeStamp() << endl;
         cout << "CPU pointer: " << CPU->getPageNum() << " " << CPU->getPID() << " " << CPU->getTimeStamp() << endl;

       }
       else {
        // ....
       }
}

“CPU指针”将与Process对象相同,因为它位于函数中,这就是我想要的。我明白了:

0 1 1
0 1 1

我有另一个只输出CPU属性的函数:

void DiskSched::currentCPU() {
   cout << endl;
   cout << "Page #: " << CPU->getPageNum() << endl
        << "PID: " << CPU->getPID() << endl
        << "Timestamp: " << CPU->getTimeStamp() << endl;
}

当我调用currentCPU时,我的CPU指针的属性不一样。我明白了:

Page #: 1595623976 (should be 0)
PID: 32767 (should be 1)
Timestamp: 1595624103 (should be 1)

我相信当我将CPU分配给向量中第一个对象的地址时,它只是用于该函数调用,它实际上并没有改变我的私有CPU指针。我该如何解决这个问题?

0 个答案:

没有答案
相关问题