Arrays- getting a 1D array from a 2D array

F

frankjones

Hi
I want to pass a 'slice' of a 2 dimensional array to a function that
accepts arrays of only 1 dimension. In C++ this is quite simple as
you just pass the array and miss out one of the dimensions.

In C# I can't get this to work. Does anyone know the best way to do
this?

(exmaple below of the code that won't work in C#)

public bool CreateData()
{
Single[,] multiData = new Single[50, 10];

ProcessData(ref multiData[50]);
}



public void ProcessData(ref Single[] rawData)
{
foreach(int s in rawData)
{
Console.WriteLine(s);
}
}

Many Thanks,
 
M

miher

Hi,

The two dimensional array You using is not exactly what You have seen in
c++. C# allows two ways to create multidimensional arrays.
1., using "rectangular" arrays. This what You have done. As i see these
array can be thinked about as if one would simulate 2d arrays in c++, by
allocating an n*m sized block.
2., using "jagged"arrays. These arrays are arrays of arrays, and as i know
these work like c++ multidimensional arrays.

public void CreateData()
{
Single[][] multiData2 = new Single[50][];
for (int i = 0; i < 50; i++)
multiData2 = new Single[10];

ProcessData(multiData2[7]);

}
publicvoid ProcessData(Single[] rawData)
{
foreach (int s in rawData)
{
Console.WriteLine(s);
}
}

Hope You find this useful.
-Zsolt
 
G

Göran Andersson

Hi
I want to pass a 'slice' of a 2 dimensional array to a function that
accepts arrays of only 1 dimension. In C++ this is quite simple as
you just pass the array and miss out one of the dimensions.

In C# I can't get this to work. Does anyone know the best way to do
this?

(exmaple below of the code that won't work in C#)

public bool CreateData()
{
Single[,] multiData = new Single[50, 10];

ProcessData(ref multiData[50]);
}



public void ProcessData(ref Single[] rawData)
{
foreach(int s in rawData)
{
Console.WriteLine(s);
}
}

Many Thanks,

In C++ an array is just a pointer to the data, while in .NET an array is
an object that contains the data. In C++ you can just make another
pointer (multidata[50] is the same thing as multidata+50*sizeof(Single))
and use it as an array, but in .NET it actually has to be a real array
object.

You can't treat a part of an array as another array, you either have to
copy the data to a new array, or use a jagged array instead of a two
dimensional array so that the second dimension are arrays objects from
the start.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top