4

I have an somewhat basic question regarding multidimensional arrays in C#.

Currently I have the following array:

float[] matrix = new float[16];

I need to create instead a 2D array with each line containing the previously mentioned 16 float numbers. Also, the number of lines in the 2D array is not known at the start of the program (i.e. it will be based on a variable).

How can I create such an array using an efficient data structure?

2
  • 2
    Does it have to actually be an array? Could it be a list of arrays instead? Commented Feb 27, 2014 at 13:13
  • If what you want is an efficient structure, don't use arrays. Create a class or a struct to represent your data instead. Commented Feb 27, 2014 at 13:14

3 Answers 3

1

You could do something like this:

const Int32 arraySize = 16;
var list = new List<float[]>();

Which gives you an empty list containing zero elements (arrays) to start. As you need to add new arrays you would write this:

var array = new float[arraySize];
// do stuff to the array

And then add it to the list:

list.Add(array);
Sign up to request clarification or add additional context in comments.

1 Comment

That was exactly what I needed, thanks Yuck and everyone else for your feedback!
1

To store 16 float numbers, you could use a 4x4 matrix (which is a 4x4 2-dimensional array). For more details, check out this documentation.

// init the array
float[,] matrix = new float[4,4];

// loop through the array
for(int col = 0; col < matrix.GetLength(0); col++)
  for(int row = 0; row < matrix.GetLength(1); row++)
     Console.WriteLine(matrix[col, row]); 

Comments

1

You can use multidimentional array syntax

float[,] arr2D = new float[12,12];

Alternatively, you could use a loop

float[][] floats = new float[12][];
for(int i=0; i< 12; i++)
{
floats[i] = new float[12];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.