【问题标题】:How to assign 1st dimension of a 2D array to a pointer如何将二维数组的第一维分配给指针
【发布时间】:2020-08-03 13:21:58
【问题描述】:

我有一个二维数组,我正在尝试将该二维数组的第一个维度分配给如下所示的指针,但这不起作用。

fixed (byte* fixedInput = array2D[0])

我怎样才能像我试图做的那样只将第一个维度分配给fixedInput

fixedInput 将成为一维指针数组,其中包含来自array2D 第一维的所有信息

谢谢!

    unsafe static void testFunction()
    {
        byte[,] array2D = new byte[10, 100];

        fixed (byte* fixedInput = array2D[0])
        {
        }
    }

【问题讨论】:

    标签: c# arrays pointers unsafe-pointers


    【解决方案1】:

    你不能。它是一个指向内存的指针。二维数组的数据按照最后一维的顺序排列,位置紧挨着。

    当你得到一个指针时,你就按照它被填充的方式跟踪内存。

    如果您想沿另一个维度读取数据,则需要大步前进,跳过每一行。

    public unsafe static void testFunction()
    {
        uint[,] array2D = new uint[10, 100];
        for(int x=0;x<100;x++)
        {
            for(int y=0;y<10;y++)
                array2D[y,x] = (uint)(1000u*y+x);
        }
    
        // read some data along first dimension.
        fixed (uint* fixedInput = &array2D[1,90])
        {
            for(int j=0;j<5;j++)
                System.Console.WriteLine(string.Format("{0}",fixedInput[j*100]));
    }
    

    样本数组中的数据以这种方式排列在内存中:

    0   1   2   3   4 [...] 99  1000  1001  1002 [...]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多