首页 > 解决方案 > 指针数组出现问题并尝试调整大小

问题描述

首先,让我说这是一个任务,我不允许使用向量。

我试图做的是调整包含对象的 2 个指针数组的大小。数组 custArray 有 3 个元素,数组 gArray 有 1 个。我需要将一个特定对象从 custArray 移动到 gArray 并将其从 custArray 中删除(所以它们都有 2 个元素),所以我创建了 2 个临时数组来更改,然后最终设置为等于 custArray 和 gArray。

void setPreferred(string id, int cSize, int pSize, Customer *custArray, Gold *gArray)
{
   int count = 0;
   Customer *temp1 = new Customer[cSize - 1];
   Gold *temp2 = new Gold[pSize + 1];
   *temp2 = *gArray;
   for(int i = 0; i < cSize; i++)
      {
         if(custArray[i].getID() == id)
            {
               temp2[pSize].setName(custArray[i].getFirstName(), custArray[i].getLastName());
               temp2[pSize].setID(custArray[i].getID());
               temp2[pSize].setTotal(custArray[i].getTotal());
               temp2[pSize].setDiscount(0.5);
               //cout << temp2[1].getName() << " " << temp2[1].getID() << " " << temp2[1].getTotal() << " " << temp2[1].getDiscount() << endl;
            }

         if (custArray[i].getID() != id)
            {
               temp1[count].setName(custArray[i].getFirstName(), custArray[i].getLastName());
               temp1[count].setID(custArray[i].getID());
               temp1[count].setTotal(custArray[i].getTotal());
               count++;
            }
      }
   //cout << temp1[0].getName() << " " << temp1[0].getID() << " " << temp1[0].getTotal() << endl;
   //cout << temp1[1].getName() << " " << temp1[1].getID() << " " << temp1[1].getTotal() << endl;

   delete [] custArray;
   delete [] gArray;

   *custArray = *temp1;
   *gArray = *temp2;
}

2个原始数组在main中定义为

Customer *customerArray = new Customer[customerSize];
Gold *goldArray = new Gold[preferredSize];

数组 temp1 和 temp2 在函数中工作正常,cout 语句打印所有正确的信息。但是,当我尝试在 main 中打印 customerArray[1] 的任何成员时,它会显示不正确的信息,并且 goldArray[1] 的成员会抛出 bad_alloc 错误。我想这意味着我删除或重新分配数组的方式有问题。任何帮助,将不胜感激。

标签: c++arrayspointers

解决方案


指针被删除后不能取消引用。如果你这样做,可能会发生意想不到的事情。


推荐阅读