Dynamic 2d Array non contiguous memory c++

旧巷老猫 提交于 2020-01-04 13:12:29

问题


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:


  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];
    



回答2:


In all cases you mention, there'll never a guarantee that you'll get contiguous memory locations for two adjacent rows. Think about this: what if after N memory cells is allocated for the first row and then the next N cells are occupied? Then the second row won't be contiguous to the first row. But this case will be rare if your 2D array is small.



来源:https://stackoverflow.com/questions/14972951/dynamic-2d-array-non-contiguous-memory-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!