如何复制在C载体? [英] How to replicate vector in c?
问题描述
在C以前的日子++和矢量/列表,当他们需要存储更多的数据他们是如何扩大数组的大小?
In the days before c++ and vector/lists, how did they expand the size of arrays when they needed to store more data?
推荐答案
典型的C code是这样的:
Typical C code looks like this:
void* newMem = realloc(oldMem, newSize);
if(!newMem)
{
// handle error
}
oldMem = newMem;
请注意,如果realloc的失败则返回零,但旧内存仍然有效,这个典型的使用会导致内存泄漏:
Note that if realloc fails then it returns zero but the old memory is still valid, this typical usage causes memory leak:
oldMem = realloc(oldMem, newSize);
if(!oldMem)
{
// handle error
}
不幸的是这是非常常见的;
Unfortunately it is very common;
另外请注意,没有什么特别的C ++矢量/列表。类似的结构可以用C实现的,只是语法(和错误处理)看起来不同。例如看性病载体:: LodePNG的模拟对C
Also note that there is nothing special about C++ vector/list. Similar structures can be implemented in C, just the syntax (and error handling) look different. For example see LodePNG's analog of std::vector for C.
这篇关于如何复制在C载体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!