c++ - 指针数组出现问题并尝试调整大小
问题描述
首先,让我说这是一个任务,我不允许使用向量。
我试图做的是调整包含对象的 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 错误。我想这意味着我删除或重新分配数组的方式有问题。任何帮助,将不胜感激。
解决方案
指针被删除后不能取消引用。如果你这样做,可能会发生意想不到的事情。
推荐阅读
- javascript - 在 Nodejs 中使用 Lua 脚本的 Redis mget
- awk - 如何使用 AWK 从文件中读取并输出到 html 表
- react-native - Expo Eject 可在 iOS 上运行,但不能在 Android 上运行
- angular - 如何在 ag-grid cellRendererParams 动作中显示鼠标悬停的文本
- python-3.x - 对分隔值应用查找并重新加入熊猫
- oracle - 使用循环比较 PL/SQL 表中单列的值
- java - 简化 java 流以查找重复属性
- json - 如何更新 JSON 值?
- go - 使用 go-sqlmock 模拟 gorm `updates` 时出现`could not match actual sql` 错误?
- python-3.x - 无法在python的exec命令中执行if语句