简体   繁体   English

动态增加/减少阵列大小

[英]Dynamically increase/decrease array size

I'm trying to increase the size of an array dynamically. 我正在尝试动态增加数组的大小。 Is there any standard C or C++ function, which appends additional space at the end of an array or removes it? 是否有任何标准的C或C ++函数,可以在数组末尾附加额外的空间或将其删除? I know, this is difficult, since it cannot be assured that there is enough space at the end on the heap. 我知道,这很困难,因为不能保证堆的末尾有足够的空间。 But shouldn't this be the job of an operating system? 但这不应该是操作系统的工作吗?

The function you're looking for is realloc() in C, which is also present in the C++ STL as std::realloc 您要查找的函数是C中的realloc() ,在C ++ STL中也以std::realloc

Though as you mentioned C++, you could also go for an standard container like std::vector which encapsulate the associated memory management. 尽管正如您提到的C ++,您也可以使用标准容器(如std::vector封装相关的内存管理。

There is no C functions as such. 没有这样的C函数。 you can go for C++ container. 您可以使用C ++容器。 This has Arrays, lists etc... 它具有数组,列表等。

可能您可以通过编写自己的内存管理包装器来实现此目的,这种包装器可以从分配的数组中追加/释放内存块。

After much experimentation by folks like professors and engineers (that have real jobs over some number of years,) when expanding an array, expand it by 50% unless you have inside information that tells you different. 经过教授和工程师之类的人的大量实验(他们已经从事了多年的实际工作),在扩展数组时,除非您掌握的内部信息告诉您不同,否则将其扩展50%。 realloc() does all the heavy lifting for you too (explained next.) From the Internet:--> The realloc() function changes the size of the memory block pointed to by ptr to size bytes. realloc()也为您完成了所有繁重的工作(接下来说明。) 从Internet:-> realloc()函数将ptr指向的内存块的大小更改为size字节。 The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. 从区域开始到新旧大小的最小值之间的内容将保持不变。 If the new size is larger than the old size, the added memory will not be initialized. 如果新的大小大于旧的大小,则不会初始化添加的内存。 If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; 如果ptr为NULL,则对于所有size值,该调用等效于malloc(size);否则,该调用等效于malloc(size)。 if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). 如果size等于零,并且ptr不为NULL,则该调用等效于free(ptr)。 Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). 除非ptr为NULL,否则它必须已经由对malloc(),calloc()或realloc()的更早调用返回了。 If the area pointed to was moved, a free(ptr) is done. 如果指向的区域已移动,则执行free(ptr)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM