从指针队列访问struct的成员

时间:2018-02-03 23:22:40

标签: c++ pointers struct

我在尝试为我的struct,PCB的成员变量赋值时遇到问题。我正在使用指向我的struct的指针队列。所以我首先取消引用传递给inititiate_process函数的指针,然后尝试将指针从ready_queue推迟到访问成员变量。如何访问此成员变量?我在这行代码(static_cast<PCB*>(ready_queue->front()))->next_pcb_ptr = &pcb;上收到了“无效的类型转换”。

这是头文件中的结构

#ifndef PCB_H
#define PCB_H

struct PCB {
    int p_id;
    int *page_table_ptr;
    int page_table_size;
    int *next_pcb_ptr;
};
#endif // !PCB_H

这是我的源cpp文件

#include <iostream>
#include <queue>
#include "PCB.h"

using namespace std;

void initiate_process(queue<int*>* ready_queue) {
    // allocate dynamic memory for the PCB
    PCB* pcb = new PCB;

    // assign pcb next
        if(!(ready_queue->empty())){
            // get prior pcb and set its next pointer to current
            (static_cast<PCB*>(ready_queue->front()))->next_pcb_ptr = &pcb;
        }
}

void main(){
    queue<int *> ready_queue;
    initiate_process(&ready_queue);
}

1 个答案:

答案 0 :(得分:1)

您确定需要static_cast吗?我建议您在PCB.h中使用

struct PCB *next_pcb_ptr;

然后在程序的主要部分和initiate_process中,使用struct PCB *而不是int *

void initiate_process(queue<struct PCB *> *ready_queue) {

  // allocate dynamic memory for the PCB
  struct PCB *pcb = new struct PCB;

  // assign pcb next
  if(!(ready_queue->empty())){

    (ready_queue->front())->next_pcb_ptr = pcb;

  }

}
相关问题