Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert from double[][] to double[*,*]

Tags:

arrays

c#

I have a code that looks like (more or less) :

public void INeedHolidaysNow(double[,]){
     //... Code to take a break from coding and fly to Hawaii
}

double[][] WageLossPerVacationDay = new  double[10][5];

INeedHolidays(WageLossPerVacationDay); // >>throws the Exception in the Title

I found the solution on this post which consists in looping rather thant trying a savage cast

So my question is : WHY ? what happens behind the scenes in the memory allocation that prevents what may seem - at least at first glance, to be a feasible cast ? I mean structurally, both expression seem to be quite identic. What is it that I am missing here ?

EDIT: I have to use "double[ ][ ]" as it is provided by an external library.

like image 393
Mehdi LAMRANI Avatar asked Feb 10 '11 10:02

Mehdi LAMRANI


4 Answers

One is a jagged array, the other is one big block.

double[][] is an array that contains arrays of double. Its form is not necessarily rectangular. In c terms its similar to a double**

double[,] is just one big block of memory, and it is always rectangular. In c terms it's just a double* where you use myArray[x+y*width] to access an element.

like image 160
CodesInChaos Avatar answered Nov 07 '22 12:11

CodesInChaos


One is called multidimensional array (double[*,*]) and other is called jagged array (double[][]).

Here is a good discussion over differences between them.

What is differences between Multidimensional array and Array of Arrays in C#?

like image 6
decyclone Avatar answered Nov 07 '22 12:11

decyclone


Quite simply, [,] arrays (2D arrays) and [][] arrays (jagged arrays) aren't the same.

A [,] array can be visually represented by a rectangle (hence it's also known as a rectangular array), while a [][] array is a 1D array that contains other 1D arrays.

It wouldn't make much sense to be able to cast one to the other.

like image 2
BoltClock Avatar answered Nov 07 '22 12:11

BoltClock


You should define your double array like this:

double[,] WageLossPerVacationDay  = new double[3, 5];

Then it should work!

hth

like image 1
Pilgerstorfer Franz Avatar answered Nov 07 '22 11:11

Pilgerstorfer Franz