c++ - 在没有线性时间复制的情况下拆分动态分配的数组

标签 c++ arrays malloc

<分区>

我正在使用 C++ 中的数组列表,每个数组都在一个对象中,并且想拆分其中的一些。 这些是动态分配的。

我想在恒定时间内进行拆分,因为理论上是可行的: 来自

[ pointer, size1 ] 

[ pointer, size2 ]; [ other array ]; [ pointer + size2, size1-size2 ]
(+ other data each time)

我尝试使用 malloc 并简单地创建一个随着大小递增的新指针。 不出所料,由于自动释放内存,我遇到了错误。

我尝试了从第二个地址开始的 realloc,但是就像这个网站上的“malloccalloc 有什么区别”已经告诉我这是不可能的。

有没有办法避免重新复制第二部分并正确定义指针? 在我知道我可以有固定时间的地方有一个线性成本是令人沮丧的。

    class TableA
    {
     public:
      (constructor)
      void divide(int size); // the one i am trying to implement
      (other, geteur, seteur)
     private
      Evenement* _el;
      vector<bool>** _old;//said arrays
      int _size;
    }

没什么特别复杂的

最佳答案

基本上,malloc 库无法处理 malloc 内存块然后释放它的切片。

你可以做你想做的事,但你必须只在最后使用 malloc 交给你的原始指针一次释放所有内存。

例如

int* p = malloc(9 * sizeof(int));
int* q = p + 3;
int* r = p + 6;
// Now we have three pointers to three arrays of three integers.

// Do stuff with p, q, r

free(p); // p is the only pointer it is valid to free.

顺便说一句,如果这真的是关于 C++ 的,那么您可能可以使用标准的 C++ 数据结构。

关于c++ - 在没有线性时间复制的情况下拆分动态分配的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20147535/

相关文章:

c - 最大分配大小

c++ - 如何计算点 o 填充/未填充矩形的距离

c++ - QString::replace(const QRegExp &, const QString &) 和 QString::replace(const QRegularExpression &, const QString &) 工作方式不同

python - 保证非零相等时的 Numpy 二维数组联合

php - 将 MySQL 中的 100 万条记录查询到 PHP 中的数组中

c - 如何判断一个变量是二维数组、指针数组还是 char 的双指针?

c++ - C++ 中的简单警告框,而不是 Objective-C

c++ - 在 C++ 中以任何给定度数(例如 45 度)旋转像素数组

c - Valgrind 报告 realloc 调用内存泄漏。但无法理解为什么

C:访问另一个文件中的数组会产生段错误