从指针队列访问结构的成员

Accessing members of struct from queue of pointers

本文关键字:成员 结构 访问 指针 队列      更新时间:2023-10-16

我在尝试为结构PCB的成员变量赋值时遇到问题。我正在使用指向我的结构的指针队列。因此,我首先取消引用传递给 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);
}

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

struct PCB *next_pcb_ptr;

然后在程序和initiate_process的主要部分,使用结构 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;
  }
}