int *p=new int[4000];
for(int i=0;i<4000;i++)
p[i]=i+1;
int *tmp=new int[8000];
for(int i=0;i<4000;i++)
tmp[i]=p[i];
delete []p;
p=tmp;
当然,用realloc比较简单些,下面是MSDN上的例子:
程序代码:
Example
/* REALLOC.C: This program allocates a block of memory for
* buffer and then uses _msize to display the size of that
* block. Next, it uses realloc to expand the amount of
* memory used by buffer and then calls _msize again to
* display the new amount of memory allocated to buffer.
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main( void )
{
long *buffer;
size_t size;
if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL )
exit( 1 );
size = _msize( buffer );
printf( "Size of block after malloc of 1000 longs: %u\n", size );
/* Reallocate and show new size: */
if( (buffer = realloc( buffer, size + (1000 * sizeof( long )) ))
== NULL )
exit( 1 );
size = _msize( buffer );
printf( "Size of block after realloc of 1000 more longs: %u\n",
size );
free( buffer );
exit( 0 );
}
Output
Size of block after malloc of 1000 longs: 4000
Size of block after realloc of 1000 more longs: 8000