Search code examples
c#arrayspointersjagged-arraysdouble-pointer

Converting from a jagged array to double pointer in C#


Simple question here: is there any way to convert from a jagged array to a double pointer?

e.g. Convert a double[][] to double**

This can't be done just by casting unfortunately (as it can in plain old C), unfortunately. Using a fixed statement doesn't seem to resolve the problem either. Is there any (preferably as efficient as possible) way to accomplish this in C#? I suspect the solution may not be very obvious at all, though I'm hoping for a straightforward one nonetheless.


Solution

  • A double[][] is an array of double[], not of double* , so to get a double** , we first need a double*[]

    double[][] array = //whatever
    //initialize as necessary
    
    fixed (double* junk = &array[0][0]){
    
        double*[] arrayofptr = new double*[array.Length];
        for (int i = 0; i < array.Length; i++)
            fixed (double* ptr = &array[i][0])
            {
                arrayofptr[i] = ptr;
            }
    
        fixed (double** ptrptr = &arrayofptr[0])
        {
            //whatever
        }
    }
    

    I can't help but wonder what this is for and if there is a better solution than requiring a double-pointer.