【问题标题】:Accessing members of struct from queue of pointers从指针队列访问结构的成员
【发布时间】:2018-02-03 23:22:39
【问题描述】:

我在尝试为我的结构 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);
}

【问题讨论】:

  • 考虑使用std::unique_ptr&lt;T&gt; 而不是T*
  • 通过传递引用而不是指针来为自己省点麻烦。 void initiate_process(queue&lt;int*&gt;* ready_queue) -> void initiate_process(queue&lt;int*&gt;&amp; ready_queue)
  • 为什么不在队列中存储指向PCBs 的指针?您似乎正在竭尽全力让自己变得困难。
  • 不管怎样,不管你一开始做了什么转换,next_pcb_ptr 仍然是 int *&amp;pcbPCB**。我认为解决这个问题的方法是停下来重新思考你在做什么。
  • 请不要编辑问题以显示正确的解决方案,因为如果您这样做,答案将不再有意义。我已经备份了你的一些编辑。如果您觉得需要在问题中添加 cmets 或更新,请至少将它们放在旧文本之后。

标签: c++ pointers struct


【解决方案1】:

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

struct PCB *next_pcb_ptr;

然后在程序的主体部分和initial_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;

  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 2022-11-01
    • 2023-03-09
    相关资源
    最近更新 更多