本文介绍了C型2D动态数组,仅需执行一次free()操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建二维数组,而无需执行许多free()操作.

I want to build 2D-array without need to perform many free() operations.

#include <iostream>
#define un unsigned
#define ln long

un ln ** array_builder(un ln rows, un ln cols)
{
    register const un ln row_memory = cols * sizeof(un ln);
    auto array = (un ln **) malloc( rows * ( sizeof(un ln *) + row_memory ) );

// First line: The bytes of memory required to store a single row in the array
// Second line: We want to store all the pointers in the single array

    auto pointer = (void *) array[0];  // sizeof(void *) == 1. It is convenient for our purposes
    pointer += rows * sizeof(un ln *);  /* Thus we skip the first pointers in the array (their amount equals 'rows').
                                       This space is considered to store pointers of array[row] type */

    for (un ln int i = 0; i < rows; i++)
    {
        array[i] = (un ln *) pointer;  // We write pointers to each row in the array[row]
        pointer += row_memory;
    }

    return array;
// We've built 2D-array. Now we can access to the elements of this array by convenient way as array[row][col]
// Don't forget to free(array) after use
}

但是该程序无法正常工作.例如,当我尝试通过array [row] [col] = some_value更改某些值时,每次都会使程序在不同的位置崩溃.

But this program works incorrect. For example, when I try to change some value by array[row][col]=some_value it makes program crash in different places every time.

推荐答案

在C ++中,既不使用malloc和free,也不使用等效的new和delete.人们会使用适当的RAII,即无需手动释放资源.对于二维数组,将使用如下单个字段:

In C++, one does not use malloc and free nor the equivalent new and delete. One would use proper RAII, that is, no manual freeing resources.For a 2 dimensional array, one would use a single field like this:

std::vector<int> data;
data.resize(width * height);

//in case you know the amount of data at compile time use a static sized field
std::array<int, width * heigth> data;

//access a single cell
int cell = data[y * width + x];

//or obtain a pointer to a row of cells
int *rowptr = &data[y * width];
int cellinrow = rowptr[x];

与分配多行相比,这既节省了空间,又节省了时间.

This is both more space and time efficient than allocating multiple rows.

在C语言中,您将等效地使用malloc分配一个整数块或使用一个静态大小的int [width * height]数组;

In C you would equivalently allocate a single block of ints with malloc or use a static sized int[width * height] array;

请注意,切勿混用C和C ++,也不要使用register关键字或惰性#defines

Note that you should never mix C and C++ nor use the register keyword nor lazy #defines

这篇关于C型2D动态数组,仅需执行一次free()操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 06:25