How can I dynamically create an array in C#?
We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.
Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.
Dynamic arrays are very useful data structures. They can be initialized with variable size at runtime. This size can be modified later in the program to expand (or) shrink the array. Unlike fixed-size arrays and Variable Length Arrays, Dynamically sized arrays are allocated in a heap.
A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required.
I'd like to add to Natrium's answer that generic collections also support this .ToArray() method.
List<string> stringList = new List<string>();
stringList.Add("1");
stringList.Add("2");
stringList.Add("3");
string[] stringArray = stringList.ToArray();
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