Hi,
I have recently bought a copy of "Jumping into C++" and have come to chapter 14 ( dynamic memory location) and have a question.
On page 153-154 an example of dynamic allocation is given for array's of int. How would the code look like for strings or structs ?
The allocation was given by:
Code:
int *growArray (int* p_values, int *size)
{
*size *= 2;
int *p_new_values = new int[ *size ];
for ( int i = 0; i < *size; ++i )
{
p_new_values[ i ] = p_values[ i ];
}
delete [] p_values;
return p_new_values;
}
Sample Code
I tried to use this for an array of structs but failed completely... please help.
I used the following struct:
Code:
struct user{
int days;
string name;
};
and the allocation function (which does not work):
Code:
struct user *growarray (struct user *p_values, int *size)
{
*size *= 2;
struct user *p_new_values = new struct user[ *size ];
for ( int i = 0; i < *size; ++i )
{
p_new_values[ i ].name = p_values[ i ].name;
p_new_values[i].days = p_values[ i ].days;
}
delete [] p_values;
return p_new_values;
}