change array size
No, try using a strongly typed List instead.
For example:
Instead of using
int[] myArray = new int[2];
myArray[0] = 1;
myArray[1] = 2;
You could do this:
List<int> myList = new List<int>();
myList.Add(1);
myList.Add(2);
Lists use arrays to store the data so you get the speed benefit of arrays with the convenience of a LinkedList
by being able to add and remove items without worrying about having to manually change its size.
This doesn't mean an array's size (in this instance, a List
) isn't changed though - hence the emphasis on the word manually.
As soon as your array hits its predefined size, the JIT will allocate a new array on the heap that is twice the size and copy your existing array across.
How can I change the size of an array in C?
Once an array in C has been created, it is set. You need a dynamic data structure like a Linked List or an ArrayList
Change an array length without creating new one?
You can't modify the size of an existing one but you can reassign a new array to the same variable. You can do it like this.
int[] array = {1,2,3,4};
int newLength = 8;
System.out.println(Arrays.toString(array));
array = java.util.Arrays.copyOf(array,newLength);
System.out.println(Arrays.toString(array));
prints
[1, 2, 3, 4]
[1, 2, 3, 4, 0, 0, 0, 0]
If the newLength is shorter, the end items will be omitted. If it is longer, all the existing items will be copied to an array of the new length.
If you want to have a data structure that dynamically increases in size as needed, then use an ArrayList
Change array size by just adding element and no push javascript
That's just the magic that JavaScript allows. If you come from a language like Java or C, this may seem like a weird idea, but you can set the value of any index in the array at any time, and the array will expand to that size!
Consider:
var t = [];
t.length === 0;
t[10000] = 'value';
t.length === 10001;
JavaScript just handles this behind the scenes. It's worth mentioning that this behavior is not specific to JavaScript. This is seen a bit in other interpreted languages as well. Ruby, for example, allows you to do the same.
Additionally in JavaScript, length
is a writeable attribute of arrays, so you can easily truncate or clear an entire array:
var t = [1];
t[4] = 0;
t === [1, undefined, undefined, undefined, 0];
t.length = 2;
t === [1, undefined];
t.length = 0;
t === [];
Setting the length to 0 is one of the fastest and simplest ways to clear an array. It might not be the most intuitive solution, but it's my go-to.
Resize array in C# later in the program
You cannot resize an array; you must declare a new array of the desired size and copy the contents of the original array into the new array.
Update: I don't like Array.Resize
- it doesn't resize the array (as the method name would suggest), it creates a new array and replaces the reference:
static void Main(string[] args)
{
int[] a1 = new int[] { 1, 2, 3 };
int[] a2 = a1;
Console.WriteLine("A1 Length: {0}", a1.Length); // will be 3
Console.WriteLine("A2 Length: {0}", a2.Length); // will be 3
Array.Resize(ref a1, 10);
Console.WriteLine("A1 Length: {0}", a1.Length); // will be 10
Console.WriteLine("A2 Length: {0}", a2.Length); // will be 3 - not good
Console.ReadLine();
}
How to extend arrays in C#
In .NET (C#), an array isn't resizable. It's not like in JavaScript or PHP were an array is made very flexible and can be extend with arbitrary elements.
Per definition an default static array has a fix size, so you can reference an element within by using the index. ( http://en.wikipedia.org/wiki/Array_data_structure#Array_resizing )
But there you can read about dynamic array. In C# it will be the System.Collections.ArrayList-Object. ( http://en.wikipedia.org/wiki/Dynamic_array )
So what you need is either the ArrayList-Definition or a normal list or generic list. (System.Collections.Generic.List)
string[] items = new string[3] { "input1", "input2", "input3" };
string[] moreItems = new string[10] { "input4", "input5" };
// array to list
List<string> itemsList = items.ToList<string>();
itemsList.Add("newItem");
// or merge an other array to the list
itemsList.AddRange(moreItems);
// list to array
string[] newArray = itemsList.ToArray();
How to change the size of an array and insert another element?
Per C syntax, It isn´t allowed to modify the length of an static allocated array after its definition. Any attempt to do so invokes undefined behavior.
Instead, Allocate dynamic memory with malloc()
, use pointer offsets to access certain pseudo-elements and use realloc()
to resize the memory.
Copy the content of the elements 4
to 9
to the elements 5
to 10
. Now you can store 3
in the 4th
element.
One demonstrative example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 9
#define ELEM_TO_CH 4
int main(void)
{
int* feld_ptr = malloc(sizeof(int) * SIZE);
if(!feld_ptr)
{
fprintf(stderr,"Memory could not be allocated for feld_ptr!");
return 1;
}
for(int i = 0; i < SIZE; i++)
{
if (i > (ELEM_TO_CH - 2))
feld_ptr[i] = i + 1;
else
feld_ptr[i] = i;
}
printf("Before:\n\n");
for(int i = 0; i < SIZE; i++)
{
printf("feld_ptr[%d] = %d\n", i, feld_ptr[i]);
}
printf("\n\n");
feld_ptr = realloc(feld_ptr, SIZE + 1);
if(!feld_ptr)
{
fprintf(stderr,"Error at resizing memory pointed by feld_ptr!");
return 1;
}
memcpy(&feld_ptr[ELEM_TO_CH], &feld_ptr[ELEM_TO_CH-1], sizeof(int) * ((SIZE + 1) - ELEM_TO_CH));
feld_ptr[ELEM_TO_CH-1] = 3;
printf("After:\n\n");
for(int i = 0; i < (SIZE + 1); i++)
{
printf("feld_ptr[%d] = %d\n", i, feld_ptr[i]);
}
free(feld_ptr);
return 0;
}
Output:
Before:
feld_ptr[0] = 0
feld_ptr[1] = 1
feld_ptr[2] = 2
feld_ptr[3] = 4
feld_ptr[4] = 5
feld_ptr[5] = 6
feld_ptr[6] = 7
feld_ptr[7] = 8
feld_ptr[8] = 9
After:
feld_ptr[0] = 0
feld_ptr[1] = 1
feld_ptr[2] = 2
feld_ptr[3] = 3
feld_ptr[4] = 4
feld_ptr[5] = 5
feld_ptr[6] = 6
feld_ptr[7] = 7
feld_ptr[8] = 8
feld_ptr[9] = 9
Related Topics
How to Display a Popup from a Webbrowser in Another Window I Created
Cause of Error Cs0161: Not All Code Paths Return a Value
Adding Items to a List<> of Objects Results in Duplicate Objects When Using a New in a Loop
Could Not Find a Part of the Path ... Bin\Roslyn\Csc.Exe
Why Use Icollection and Not Ienumerable or List<T> on Many-Many/One-Many Relationships
Programmatically Add Column & Rows to Wpf Datagrid
Showing Difference Between Two Datetime Values in Hours
How Can a Word Document Be Created in C#
Select Multiple Items from a Datagrid in an Mvvm Wpf Project
Is Using a Mutex to Prevent Multiple Instances of the Same Program from Running Safe
Observeon and Subscribeon - Where the Work Is Being Done
Return View as String in .Net Core
Ignore Mapping One Property with Automapper
Are There Any Fuzzy Search or String Similarity Functions Libraries Written for C#
Algorithm to Compare Two Images in C#
Xml Serialization and Inherited Types
How to Write Programs in C# .Net, to Run Them on Linux/Wine/Mono