Help! I'm trying to expand an array via pointers, but my program crashes when i try to run this. It tells me that it's unable to read the "name" variable of the class.
void expandArray(Test test[],int &capacity)
{
Test* newTempArr = new Test[capacity * 2];
for (int i = 0; i < capacity; i++)
{
newTempArr[i] = test[i];
cout << newTempArr[i].toString();
}
delete[] test;
test = newTempArr;
capacity *= 2;
}
Think about what test is in the above function. test is just a pointer, right? When you pass testArray to it (function expandArray), you are creating another pointer called test which is a copy of testArray. This means that you copy the address stored in testArray to the pointer test. Since test is merely a copy, changing what test points to doesn't change what testArray points to.
1 2 3 4 5 6 7 8 9 10 11 12 13
void foo(int array[])
{
array = 0; // only this copy will be effected
}
int main()
{
// assume a is dynamically allocated
foo(a); // at this point, the pointer named array in foo and a both point
// to the same location in memory, but &a != &array, so any changes
// to the value of array itself (that is, the address that is stored in it)
// will not effect a.
}
You need to have expandArray take a pointer to a pointer, then pass the address of testArray from main:
1 2 3 4 5 6 7 8 9 10 11
void foo(int * array[])
{
*array = 0; // array will still point to a, but a will now point to nothing
}
int main()
{
// assume a is dynamically allocated
foo(&a); // now array in foo points to a which points to an array in memory.
// changes to *array will change the value of a itself
}
Hope that clears it up a little bit (I'm in a bit of a rush, so I'll come back later and offer more detail if need be)