如何处理结构中已删除的项目

时间:2016-10-22 18:44:33

标签: c++ pointers struct

我正在使用struct,因为在我的任务中我被要求这样做。我从数组中删除了一个特定的结构项,我想在删除的位置分配一个新元素,如何实现。

const int IN_USE=5;

struct process
{
    int processID; // added by user4581301 to make sample compile
};

struct ReadyQueue
{
    int size;
    struct process * Active;   // Pointer to another struct
    struct process * readyProcesses[IN_USE]; // Array of pointers
} ready;


int main()
{
    ready.Active = new struct process; // just one object
    // Allocate one object for each index in the array
    for(int i=0;i<IN_USE;i++)
        ready.readyProcesses[i] = new struct process;
    // after assigning values to all the individual processes  

    delete ready.readyProcesses[1]; // delete the second  item
    ready.readyProcesses[1] = 0; 

    int readyCount=0;     

    while(readyCount<IN_USE)
    {
        if(ready.readyProcesses[readyCount]==0) // trying to check if it is deleted
        {
            ready.readyProcesses[readyCount] = new struct process;
            // when I try to set or print  member variable gives segmentation fault 
            ready.readyProcesses[readyCount]->processID=103;
         }
         readyCount++;
    }
    return 0;
}

在上面的程序中,如果我想再次在位置1分配一个元素。我得到分段错误。如何解决这个问题。

0 个答案:

没有答案