获取数组2d中的地址位置

时间:2015-10-12 18:10:23

标签: c# c++ arrays

要在c++中获取数组的位置,您可以执行以下操作:

class Slot
{
public:

    int Color;
    std::string name;
    /*.... more properties*/
};

int main()
{
    Slot pix[60];

    Slot& randomSlot = pix[12];
    randomSlot.Color = 12;
    randomSlot.name = "sdsd";

    Slot* addressOfSlot = &randomSlot;
    Slot* arrayStart = pix;

    //get the original pos
    int x = addressOfSlot - arrayStart;
}
  1. 你会如何做到这样来获得2d array的x和y位置? :

    Slot pix[60][21];
    
  2. 我想使用这种方法,因为我将使用指针/引用,我希望有一个快速的方法来获得原始位置,

    1. 您也可以在c#中使用不安全的代码或类似的东西吗?

1 个答案:

答案 0 :(得分:1)

您可以从尺寸为(23,23.5] 0 NaN (23.5,24] 4 2.9500345 (24,24.5] 1 6.9320712 (24.5,25] 2 3.0219788 (25,25.5] 2 3.7149871 (25.5,26] 1 1.9051732 (26,26.5] 2 3.1865066 (26.5,27] 1 3.9982569 的2D数组映射到相同尺寸的1D数组,反之亦然

ROWS x COLS

其中array2D[x][y] <-> array1D[x * COLS + y]; 是列数。这使用了这样的事实:在C或C ++中,数组存储在技术上称为row-major order的内容中。 Fortran或MATLAB使用列主要顺序,因此索引是转置的。