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

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

问题描述

说我通过二维数组的地址的函数随着二维阵列的其行和列

该函数将治疗二维阵列1d的数组的地址。 (如:INT矩阵[])

如果我下面code执行:

  INT **编曲;

    ARR =新INT * [行]。

    的for(int i = 0; I<行;我++)
    {

        改编[我] =新的INT [专栏]
    }
 

  1. 或CEO,我想在多线程系统,这可能不是为二维数组分配连续的内存。我对么?

  2. 不过,我觉得在一个单线程系统,这将分配的连续内存的二维数组。我对吗?如果是这样,它是永远是真的吗?或者它依赖于编译器和操作系统?

  3. 如果在code现在是这样的:

      INT **编曲;
    INT ** ARR2;
    
    ARR =新INT * [行]。
    ARR2 =新INT * [行]。
    
    的for(int i = 0; I<行;我++)
    {
    
        改编[我] =新的INT [专栏]
        ARR2 [我] =新的INT [专栏]
    }
     

    我没有连续内存的二维数组。即使每行中的元素将是连续的,各行本身将不会被邻接的下一行。对吗?

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

解决方案
  1. 在实践中可能是真实的大部分时间,可能是实现相关的,虽然,不同的内存分配策略可能会走得差不多了不同的方法,不太可能是标准定义。也依赖于内存碎片。
  2. 同样如此。
  3. 假,因为最典型的二维数组如下,它会产生连续的堆栈存储器

      INT my2DArr [5] [5];
     

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

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

If i execute below code:

    int** arr;

    arr = new int*[row];

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

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

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

  2. 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?

  3. If the code is now this:

    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?

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

解决方案

  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天全站免登陆