开发者

Array of array initialization by using unmanaged pointers in C#

I would like to define an array of array eg int[]开发者_开发知识库[] on top of an existing int[] of the right size. I want then to seamlessy use either the int[][] array of array or the int[] 'big' array while refering to the same inner data.

Is this possible to do this in C# using unmanaged code? In C++ I would defined pointers like this :

int* bigArray = new int[numberOfRows * numberOfColumns];
int** matrix = new int*[numberOfRows];

for (int i = 0; i < numberOfRows; i ++)
{
    matrix[i] = (bigArray + i * numberOfColumns);
}


Yes, you can also use pointer in C#, but there are some limits on it. 1st, you need to declare the function with unsafe, and also, you need to set the build option to allow unsafe code in the project property, here is the sample code about it:

        unsafe static void T1(int numberOfRows, int numberOfColumns)
    {
        int* bigArray = stackalloc int[numberOfRows * numberOfColumns];
        int** matrix = stackalloc int*[numberOfRows];

        for (int i = 0; i < numberOfRows; i++)
        {
            matrix[i] = (bigArray + i * numberOfColumns);
        }

    }

Remember, you can use the pointer only if you are so clear of that you have full control of your code. while it is not recommend you use the pointer in C#


You can do it in managed code, using a class as a wrapper and providing it with an indexer:

class Matrix
{
    public readonly int[] BigArray;   // make available
    private int _rowSize = ...;

    public int this[int x, int y]
    {
       get { return BigArray [x*_rowSize+y]; }
       set { BigArray [x*_rowSize+y] = value; }
    }
}

Edit:

changed arrray into public readonly field so that the class has a dual interface

Edit 2:

Using T[][] to provide access to T[] rows.

class Matrix2<T>
{
    private T[][] _data;
    private int _columns;

    public Matrix2(int rows, int cols)
    {
        _data = new T[rows][];
        _columns = cols;
        for (int i = 0; i < rows; i++) _data[i] = new T[cols];
    }

    public T this [int x]
    {
        get { return _data [x/_columns][x % _columns]; }
        set { _data [x/_columns][x % _columns] = value; }
    }

    public T[] Row(int r)
    {
        return _data [r];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜