Originally Posted by
brewbuck
Sure.. But maybe at least use new instead of malloc? Unless you know you're going to be using realloc() later, I'd say use new.
I would like to mention that even then it isn't necessary to use C functions. It's even less necessary to do this at all I suppose, but
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
void print( int base[], std::size_t size )
{
for( std::size_t i = 0; i < size; ++i )
{
std::cout << ' ' << base[ i ];
}
std::cout << std::endl;
}
int main( )
{
const std::size_t ORIG_SIZE = 4;
const std::size_t NEW_SIZE = 8;
// 1) Build an array of some size.
int *bar = new int[ ORIG_SIZE ];
std::time_t now;
std::time( &now );
std::srand( now );
// 2) Use the array however you like.
for( std::size_t i = 0; i < ORIG_SIZE; ++i )
bar[ i ] = std::rand( );
std::cout << "Before: ";
print( bar, ORIG_SIZE );
// 3) Make a temporary array.
int *temp_bar = new int[ ORIG_SIZE ];
// 4) Copy objects over to this array.
for( std::size_t i = 0; i < ORIG_SIZE; ++i )
temp_bar[ i ] = bar[ i ];
// 5) Extend the array with new after deleting the old array data.
delete [] bar;
bar = new int[ NEW_SIZE ];
// 6) Refill the extended array.
for( size_t i = 0; i < NEW_SIZE; ++i )
bar[ i ] = ( i < ORIG_SIZE )? temp_bar[ i ] : std::rand( );
delete [] temp_bar;
std::cout << "After : ";
print( bar, NEW_SIZE );
// and so on ...
// 7) Clean up when you're done!
delete [] bar;
}
/*
* My output:
*
* Before: 24197 24557 21828 14805
* After : 24197 24557 21828 14805 20141 15933 21001 9472
*/
Sorry about the bump for this...