tags:

views:

114

answers:

1

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);
}
A: 

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#

jujusharp
Is there a way to cast int** matrix to an actual int[][] and int* bigArray to int[]?Cause that's what I would like to do : declare both objects whith this given property then use them seamlessy in classical managed C# code which expects int[] and int[][].Last precision, do I have to free/delete pointers? I guess I do have to, don't I?
Guillaume
You need to __pin__ this array during it's entire lifetime.
Henk Holterman
Sorry, I can't get what exactly you wanna to do, in fact, the managed code for C# now can do mostly of what the pointer can do, so I think you'd better try to implement what you want to do without these unsafe code. BTW, you needn't to free the pointers because the GC will do this work if the pointer was out of scope. Sorry Not hlep you so much.
jujusharp
Well, I probably make myself not clear, but the managed solution doesn't do it because it doesn't actually prodide an int[][] object pointing to the same data as in the int[] object. Your solution is closer so far! But thanks a lot both of u for your answers
Guillaume