How can I define two dimensional dynamic array? If I want to use List<>, can I use it for two dimensions?
A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.
A one-dimensional array can be seen as data elements organised in a row. A two-dimensional array is similar to a one-dimensional array, but it can be visualised as a grid (or table) with rows and columns. Many games use two dimensional arrays to plot the visual environment of a game.
The malloc() function is used in c programming to store the data in the heap which is dynamic memory storage. It is mostly used for the dynamic declaration of the arrays and also be used for the creation of two-dimensional arrays.
There's no built-in dynamic equivalent of two-dimensional arrays that I'm aware of, but you can easily get at more or less the same functionaltiy.
Define a Coordinate class with this API:
public class Coordinate : IEquatable<Coordinate>
{
public Coordinate(int x, int y);
public int X { get; }
public int Y { get; }
// override Equals and GetHashcode...
}
You can now create a collection of these Coordinate instances.
If you create a HashSet<Coordinate>
you will be guaranteed that you cannot add a Coordinate if it's already added because it overrides Equals.
If you want, you can expand Coordinate to Coordinate<T>
like this:
public class Coordinate<T> //...
{
// previous stuff...
public T Item { get; set; }
}
This will allow you to associate a strongly typed item with each coordinate, like this:
var items = new HashSet<Coordinate<string>>();
items.Add(new Coordinate<string>(1, 4) { Item = "Foo" });
items.Add(new Coordinate<string>(7, 19) { Item = "Foo" });
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With