注册 登录
编程论坛 C++教室

问一个问题

gao_gao86 发布于 2007-03-03 16:50, 392 次点击
我是个初学者,有个问题想向高手请教一下,

动态内存分配的new操作
  int* v;
......

v=new int[10];
是在内存中重新分配对应的空间,使v指向起始地址对吧?如果原来v指向一个一维数组且元素都已赋值,如果执行以上操作,是否原来数组里的值都会丢失呢?
3 回复
#2
wfpb2007-03-03 18:04

不会丢失,new是在用户可以用的空闲的内存空间中取出指定的大小分配给指针,而v原先指向一个数组,那么那个数组所在的空间还是已经被利用的(数据仍然在那里,但是没有办法访问他,造成内存泄露),而不是空闲的。那么v另外分配一个空间给他.只是告诉计算机,这块空间被标记为已使用。
new标记一块地址被使用,delete标记一块地址使用完毕(即未被使用)

#3
gao_gao862007-03-03 21:08
回复:(wfpb)不会丢失,new是在用户可以用的空闲的内...

谢谢指教, 那如果我不能确定数组的大小,如果数组满了以后我想扩大size该怎么处理呢?

#4
wfpb2007-03-04 12:10

扩大数组可以手动控制:


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

1