Hello,
I've made a program that uses an array of objects, it's work well so far, upto the point that I try to increase the size of an array.
So, in main the relevant code loops like this:
int main(){
/* classes used */
phoneBook *p;
....
numLines = 0;
....
/*
findNumLines, finds the amount of lines present
in the buffer.
Then p=... creates an array of objects
of size 'numLines'
*/
findNumLine(buffer,numLines);
p = new phoneBook[numLines];
getLine(buffer, p);
/*
Everything works upto here!
*/
....
/*IO requests take place and this function is called */
addEntry(p, numLines);
....
}
The addEntry is an IO function, it requests for a user input, puts it into a temp-values. addEntry then calls "increaseArraySize" to increase the size of p!
void addEntry(phoneBook *p, int &numLines){
.....
/*numlines is now 3. there is an array of objects that has
**numLines amount of objects*/
increaseArraySize(p, numLines, 1);
//numlines is now 4
printAll(p, numLines); //error occurs here!
....
}
So at this point, an error occurs. The increaseArraySize function, creates a temp array of objects (t). all the information in p, is copied into t. p is destroyed, and created to a new size, the new array p is populated with the info in t, and then t is deleted.
void increaseArraySize(phoneBook *p, int &numLines, int a){
/* temp */
phoneBook *t;
numLines += a;
t = new phoneBook[numLines];
for(int i = 0; i < (numLines-a); i++){
t[i] = p[i];
}
t[numLines-a].setNull();
printAll(t, numLines);
cout << "Numlines is:" << numLines <<endl;
/* delete p and re-init */
delete [] p;
p = new phoneBook[numLines];
printAll(t, numLines);
printAll(p, numLines);
p=(t);
cout <<"------------------t--------------"<<endl;
printAll(t, numLines);
cout <<"------------------p--------------"<<endl;
printAll(p, numLines);
/* delete temp array of objects */
delete [] t;
}
The printAll function prints out all the objects in the array. The print outs are correct, and are the same. This function seems to work...
THE PROBLEM
The problem is, back in the addEntry() function, the values of the objects of p aren't the same as the objects of p in the increaseArraySize() function (after deleting it and recreating it (it, as in p)).
I guess, that I'm doing the resizing incorrectly.. but i'm not sure what else to do?..
It's long winded, but I much appreciate the time you've spent reading so far :)
Thanks,
Matthew