如何用新的分配一块内存? [英] how do I allocate one block of memory with new?

查看:182
本文介绍了如何用新的分配一块内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组,我已经动态使用新分配。

I have a two dimensional array that I've allocated dynamically using new.

问题是我想将内存分配为一个连接的块,而不是分离以增加处理速度。

The problem is I want to allocate the memory as one connected block instead of in separated pieces to increase processing speed.

有人知道是否可以用新的,或者我必须使用malloc吗?

Does anyone know if it's possible to do this with new, or do I have to use malloc?

这是我的代码:

A = new double*[m];
    for (int i=0;i<m;i++)
    {
        A[i]= new double[n];
    }

此代码会导致细分错误 >

This code causes a segmentation fault

phi = new double**[xlength];
phi[0] = new double*[xlength*ylength];
phi[0][0] = new double[xlength*ylength*tlength];
for (int i=0;i<xlength;i++)
{
    for (int j=0;j<ylength;j++)
    {
        phi[i][j] = phi[0][0] + (ylength*i+j)*tlength;
    }
    phi[i] = phi[0] + ylength*i;
}


推荐答案

并适当地使用它,像这样:

You can allocate one big block and use it appropriately, something like this:

double* A = new double[m*n];
for (int i=0; i<m; i++) {
    for (int j=0; j<n; j++) {
        A[i*n+j] = <my_value>;
    }
}

而不是使用 / code>,你可以使用 malloc - 没有太大的区别,除了 new delete malloc() >。

Instead of using new, you can use malloc - there is no much difference, except that new must be released with delete, and malloc() released with free().

UPDATE1
您可以按如下所示创建true2d数组:

UPDATE1: You can create "true" 2d array as follows:

double** A = new double*[m];
double*  B = new double[m*n];
for (int i=0; i<m; i++) {
    A[i] = B + n*i;
}
for (int i=0; i<m; i++) {
    for (int j=0; j<n; j++) {
        A[i][j] = <my_value>;
    }
}

只要一定要释放

Just be sure to release both A and B in the end.

UPDATE2

根据热门请求,这是如何创建true三维数组(尺寸 m x n x o ):

By popular request, this is how you can create "true" 3-dimensional array (with dimensions m x n x o):

double*** A = new double**[m];
double**  B = new double*[m*n];
double*   C = new double[m*n*o];
for (int i=0; i<m; i++) {
    for (int j=0; j<n; j++) {
        B[n*i+j] = C + (n*i+j)*o;
    }
    A[i] = B + n*i;
}
for (int i=0; i<m; i++) {
    for (int j=0; j<n; j++) {
        for (int k=0; k<o; k++) {
            A[i][j][k] = <my_value>;
        }
    }
}

索引数组 A B 和数据数组 C 。像往常一样,所有三个应该在使用后释放。

This uses 2 relatively small "index" arrays A and B, and data array C. As usual, all three should be released after use.

扩展这个更多的维度留给读者练习。

Extending this for more dimensions is left as an exercise for the reader.

这篇关于如何用新的分配一块内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆