如果一个数组空间太小了,要分配一个大数组......

nothing707 2003-02-21 01:37:50
如何来分配一个新的、更大的数组,然后把前一个小数组,复制到大数组上去。
释放小数组所占的空间。想了半天没有想出来,敬听各位高见。
...全文
74 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunriselx 2003-02-21
  • 打赏
  • 举报
回复
用stl的容器,插入时自动在堆上分配内存
earthharp 2003-02-21
  • 打赏
  • 举报
回复
#include <iostream>
#include <iomanip>
#include <vector>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <algorithm>


using namespace std;


void Print(int a)
{
std::cout << a << " ";
}
int main()
{
int* pi = reinterpret_cast<int*>(malloc(100 * sizeof(int)));
*pi = 1;
pi = reinterpret_cast<int*>(realloc(pi, 1000 * sizeof(int)));

std::cout << *pi << std::endl;
free(pi);

vector<int> vi;
vi.push_back(33);
vi.push_back(22);
vi.push_back(11);
vi.push_back(2356);

vi.resize(200, 0);

for_each(vi.begin(), vi.end(), Print);
}
nothing707 2003-02-21
  • 打赏
  • 举报
回复
要例子fangrk:)
fangrk 2003-02-21
  • 打赏
  • 举报
回复
用vector
nothing707 2003-02-21
  • 打赏
  • 举报
回复
earthharp:
你也来个例子呀~
earthharp 2003-02-21
  • 打赏
  • 举报
回复
realloc或者
重新new 一个数组再使用memmove或者memcpy.
brave_heart 2003-02-21
  • 打赏
  • 举报
回复
/* 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 );
}

北极猩猩 2003-02-21
  • 打赏
  • 举报
回复
在C++中没有特殊要求的话干脆使用vector算了,根本不需要考虑空间够不够的问题

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧