动态二维数组非连续内存 C++ [英] Dynamic 2d Array non contiguous memory c++

查看:35
本文介绍了动态二维数组非连续内存 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我将二维数组的地址连同二维数组的行和列一起传递给函数.

Say I passed the address of the 2d array to a function along with its row and column of the 2d array.

该函数会将二维数组的地址视为一维数组.(例如 int matrix[] )

The function will treat the address of the 2d array as 1d array. (eg. int matrix[] )

如果我执行以下代码:

    int** arr;

    arr = new int*[row];

    for ( int i = 0; i < row; i++ )
    {

        arr[i] = new int[column];
    }

  1. 假设,我认为在多线程系统中,这可能不会为二维数组分配连续的内存.我对么?

  1. Hypothetically, I think in a multi-threaded system, this may not allocate contiguous memory for the 2d array. Am I correct?

但是,我认为在单线程系统中,这将为二维数组分配连续的内存.我对吗?如果是这样,它总是"真的吗?还是取决于编译器和操作系统?

However, I think in a single threaded system, this will allocate contiguous memory for the 2d array. Am I right? If so, is it "always" true? or does it depend on the compiler and the OS?

如果代码现在是这样:

int** arr;
int** arr2;

arr = new int*[row];
arr2 = new int*[row];

for ( int i = 0; i < row; i++ )
{

    arr[i] = new int[column];
    arr2[i] = new int[column];
}

我没有连续的内存二维数组.即使每一行中的元素是连续的,行本身也不会与下一行连续.我说得对吗?

I do not have contiguous memory 2d arrays. Even if the element in each row will be contiguous, the rows itself won't be contiguous with the next row. Am I correct?

如果以上都是正确的,在 C++ 中,不是每个二维数组都是连续的内存,对吗?

If all above are correct, in C++, not every 2d array is contiguous memory, right?

推荐答案

  1. 真的
  2. 大部分时间实际上可能是正确的,虽然可能取决于实现,但不同的内存分配策略可能会以不同的方式进行,不太可能是标准定义的.还取决于内存碎片.
  3. 再说一遍.
  4. 错误,因为最典型的二维数组如下所示,它将具有连续的堆栈内存

  1. True
  2. Practically probably true much of the time, likely to be implementation dependant though, different memory allocation strategies might go about it different ways, unlikely to be standard defined. Also dependant on memory fragmentation.
  3. Again true.
  4. False, since the most typical 2D array is as below and it will have contiguous stack memory

int my2DArr[5][5];

这篇关于动态二维数组非连续内存 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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