This question already has answers here:
Differences between a multidimensional array "[,]" and an array of arrays "[][]" in C#?
(12 answers)
Closed 7 years ago.
The syntax is slightly different but what is the difference between them.
public static string[][] str1 = { new string[] { Total, "N2" }};
public static string[,] str2 = { { Total, "N2" } };
What are the guidelines for the use of each?
Have a look here:
https://msdn.microsoft.com/en-us/library/2s05feca.aspx
Basically, the difference is how the memory is allocated.
[,] notation will allocate all of the needed memory in one block, while [][] notation will allocate an array of pointers to arrays, where each array is allocated separately and not necessarily next to the others
In the examples you quoted:
public static string[][] str1 = { new string[] { Total, "N2" }};
public static string[,] str2 = { { Total, "N2" } };
The first one is an array of arrays (Jagged Array). Each entry can point to an array of string.
The second one is a normal 2 dimensional array (Multi Dimensional Array).
In a nutshell , [,] is a 2d array allocated all at once, while [][] is an array of arrays thus memory allocation is gradual- the initialization syntax (as you pointed out) is different also.
One more important difference is that in a [][] type you can define each 'row' of a different size. which you can't do in [,] which is in a way a C# representation of a Matrix.
Related
This question already has answers here:
Copy Arrays to Array
(7 answers)
Closed 1 year ago.
In C# and many other languages, if you pass an array to a function it passes the pointer/reference which means you can change the value of an array from inside a function.
From Microsoft:
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
I have a special case where I need to access and change an array's contents from a function but I do not want to change the original array. I thought this would be quite simple. I could set a new array equal to the old array and change the new array. This acts the same, however, because the new array is just a pointer to the old one.
static void AddToArray(string[] array) {
var newArray = array;
newArray[2] = "y";
}
static void Main(string[] args) {
string[] array = new string[5];
array[0] = "h";
array[1] = "e";
AddToArray(array);
}
If you print the contents of array at each step:
"he"
"hey" (inside function)
"hey" (after function call)
I've done a lot of research online but somehow haven't found many other people who needed help with this. Advice is greatly appreciated!
You are not creating your array using "new" Keyword inside function. Change below line -
var newArray = array;
To
var newArray = new string[args.Length];
and after creating this as a new array, you can copy the values from args (passed) array
I'm a little bit confused. I try to assign a string array to a two dimensional string array. But get "Wrong number of indices" error.
I understand the error, but should it not be possible to assign an array to the second dimension array field?
As sortedString has x number of fields with each an string array, should it not be possible to assign an string array to just a indexed field? (as the s.Split(';') already creates an array)
string[,] sortedString = new string[count,columns];
sortedString[counter] = s.Split(';');
You're confusing a multidimensional array with a jagged array. sortedString is a 2-dimensional array of type string, so you must always provide the correct number of indices - in this case, 2. You can't say sortedString[x], you can only say sortedString[x, y].
You're probably thinking of a jagged array - i.e., a single-dimensional array, where each element is itself a (usually single-dimensional) array. Declare sortedString like this:
string[][] sortedString = new string[count][];
This will allow each "inner" array to be of a different length (depending on how many ; there are in each s), which might not be what you want.
C# has two kinds of 2D arrays. If you need access to one dimension at a time as it's own array, you must use the "jagged" variety, like this:
string[][] sortedString = new string[count][];
for(int i = 0; i<sortedString.Length;i++)
sortedString[i] = new string[columns];
Or, even better:
var sortedString = new List<string[]>;
I have a two dimensional array declared. It has two columns - filename and batch. I initialize it empty.
string[,] a_Reports = new string[,] { { "", "" } };
I have some code that resizes it and populates it. Everything is a string value. When I go to look up an element in the array like so:
int value1 = Array.Find<string>(a_Reports, element=>element.Equals(newFileName));
I get the error:
CS1503 Argument 1: cannot convert from 'string[*,*]' to 'string[]'
I've tried it every which way and nothing works. Please help me!!! I've spent hours on it already.
Array.Find is only for one-dimensional arrays. (MSDN)
Check out this answer on 'How do I search a multi-dimensional array?'
Produce a similar extension method, like in my example on rextester.
Or use a jagged array instead of a two-dimensional one and a combination of foreach and find, like:
string[][] jagged = ...
Array.ForEach(jagged, array=>Array.Find(array, x=>x=="" ));
This question already has answers here:
Reverse elements in an array
(6 answers)
Closed 6 years ago.
I need to create a function that receives an array items and reverses the order of items in the array and returns it.
Basically if I have an array ['cat', 'dog', 'bird', 'worm'] the function should return an array of ['worm','bird','dog','cat'].
So far I get lost in the function language... I have this.
//Split a string into an array of substring
string avengersNames = "Thor;Iron Man;Spider-Man;Hulk;Hawk Eye";
//Creat an array to hold substring
string[] heroArray = avengersNames.Split(';');
foreach (string hero in heroArray)
{
Console.WriteLine(hero);
}
//Parameter is Array of items
//At a loss when trying to incorporate an array into this function.
public static string[] heroList = new string[5];
{
}
Array.Reverse(heroArray); // can do trick for you
Use Array.Reverse function
string[] heroArray = avengersNames.Split(';');
Array.Reverse(heroArray );
This question already has answers here:
Two dimensional array slice in C#
(3 answers)
Closed 8 years ago.
Following situation:
I have a Array which got 2 dimension. No i want to access the second dimension. How can i achieve this goal?
Here my code to clarify my problem:
private static int[,] _Spielfeld = new int[_Hoehe, _Breite];
private static bool IstGewonnen(int spieler)
{
bool istGewonnen = false;
for (int zaehler = 0; zaehler < _Spielfeld.GetLength(0); zaehler++)
{
//Here i cant understand why compiler doesnt allow
//Want to give the second dimension on the Method
istGewonnen = ZeileSpalteAufGewinnPruefen(_Spielfeld[zaehler] ,spieler);
}
return istGewonnen;
}
//This method want to become an Array
private static bool ZeileSpalteAufGewinnPruefen(int[] zeileSpalte, int spieler)
{
//Some further code
}
The compiler is saying: "Argument from type int[,] is not assignable to argument of type int[]. In Java it is working as i expected. Thanks in advance.
Define your array as a jagged array (array of arrays):
private static int[][] _Spielfeld = new int[10][];
Then loop through the first dimension and initialize.
for (int i = 0; i < _Spielfeld.Length; i++)
{
_Spielfeld[i] = new int[20];
}
Then the rest of your code will compile OK.
C# allows two different offers two flavors of multidimensional arrays which, although they look quite similar, handle quite differently in practice.
What you have there is a true multidimensional array, from which you cannot automatically extract a slice. That would be possible (as in Java) if you had a jagged array instead.
If the choice of having a multidimensional array is deliberate and mandatory then you will have to extract slices manually; for example see this question.
If the choice between jagged and multidimensional is open then you can also consider switching to a jagged array and getting the option of slicing for free.