我在使用这个程序时遇到了一些问题,我知道我可以使用矢量,但我只是尝试使用数组。一旦程序达到初始数组大小1000,它应该在复制数据后将数组加倍(在本例中为2000)。因此,例如,如果我有一个包含3000个名称的列表,它会在1000处加倍,然后再在2000处加倍 - 使总列表4000.我不完全确定为什么在我将数组大小加倍后它会崩溃。有人可以帮我这个吗?
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
struct Information {
char functionality;
string SSN;
string name;
};
Information* person;
int numPeople = 1000;
int numRetrieved = 0;
int numArray = 0;
int numInserted = 0;
int numDeleted = 0;
void doubleArray(Information *person){
numPeople = numPeople * 2;
Information* temp = new Information[numPeople];
memcpy(temp, person, numPeople/2);
delete[] person;
person = temp;
cout << "Person 1: " << person[0].name << " " << person[0].SSN << endl;
}
//Currently not using this until I figure out the double...
void halfArray(Information *person){
numPeople = numPeople / 2;
}
void deleteInfo(Information *person, string SSN){
for(int i = 0; i < numArray; i++){
if(person[i].SSN == SSN){
for(int k = i; k < numArray-1; k++){
person[k].SSN = person[k+1].SSN;
person[k].name = person[k+1].name;
}
numArray--;
numDeleted++;
if((numArray+1) < (numPeople / 4)){
//halfArray(person);
}
}
}
}
void retrieve(Information *person, string findSSN, int lastPerson){
for(int i = 0; i < lastPerson; i++){
if(person[i].SSN == findSSN){
numRetrieved++;
}
}
}
void insert(Information *person, string SSN, string name){
if(numArray == (numPeople - 1)){
doubleArray(person);
}
bool dontInsert = false;
for(int i = 0; i <= numArray; i++){
if(person[i].SSN == SSN){
dontInsert = true;
}
}
if(dontInsert){
dontInsert = false;
}else{
person[numArray].SSN = SSN;
person[numArray].name = name;
numArray++;
numInserted++;
}
}
int main(int argc, char* argv[]) {
person = new Information[numPeople];
char firstLetter;
string SSN, firstName, lastName, name;
fstream input(argv[1]);
for(int i = 0; !input.eof(); i++){
input >> firstLetter >> SSN >> firstName >> lastName;
name = firstName + " " + lastName;
switch(firstLetter){
case 'd':{
deleteInfo(person, SSN);
break;
}
case 'i':{
insert(person, SSN, name);
break;
}
case 'r':{
retrieve(person, SSN, numArray);
break;
}
}
}
input.close();
}
答案 0 :(得分:0)
您删除了Information*
所指向的内存,但是您拥有该指针的副本,并将其分配给temp
变量在doubleArray
之外无效。
让我们说传入的人的价值是0xC001C001;
void doubleArray(Information *person){
numPeople = numPeople * 2;
Information* temp = new Information[numPeople];
memcpy(temp, person, numPeople/2);
delete[] person;
person = temp;
cout << "Person 1: " << person[0].name << " " << person[0].SSN << endl;
}
您创建一个新的指针temp,其值为0xBAD1BAD1。删除人(0xC001C001),然后将0xBAD1BAD1分配给person。然后在插入函数中继续执行...
void insert(Information *person, string SSN, string name){
if(numArray == (numPeople - 1)){
doubleArray(person);
}
bool dontInsert = false;
for(int i = 0; i <= numArray; i++){
if(person[i].SSN == SSN){
dontInsert = true;
}
}
此处的person变量仍具有已取消分配的值0xC001C001。当您使用person[i].SSN
推荐人时,您的计划会爆炸。
当您想要更改指针时,经典模式是传递指针指针。 (两星级节目)
void redo(P** p)
{
P* temp = new P();
delete *p;
*p = temp;
}