Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I initialize an array to size 0?

Tags:

arrays

c#

Let's say I have a function like:

void myFunc(List<AClass> theList) {    string[] stuff = new string[theList.Count]; } 

and I pass in an empty list.

Will stuff be a null pointer? Or will it be a pointer to some random place in memory that is uninitialized?

like image 766
samoz Avatar asked Jun 23 '10 14:06

samoz


People also ask

Should you initialize an array variable to 0?

Historically we would initialize an array to 0 to prevent bad data (remnants of other memory usage) from being in the array. Show activity on this post. You need to initialize it for the same reasons you would initialize any other variable, whether it's an array or not.

Can we initialize array with 0 size in Java?

Java allows creating an array of size zero. If the number of elements in a Java array is zero, the array is said to be empty. In this case you will not be able to store any element in the array; therefore the array will be empty.

What happens if we declare array without size?

Even if you do not initialize the array, the Java compiler will not give any error. Normally, when the array is not initialized, the compiler assigns default values to each element of the array according to the data type of the element.

How do you initialize an array with zero values?

Using Initializer List. int arr[] = { 1, 1, 1, 1, 1 }; The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.


1 Answers

It will create an empty array object. This is still a perfectly valid object - and one which takes up a non-zero amount of space in memory. It will still know its own type, and the count - it just won't have any elements.

Empty arrays are often useful to use as immutable empty collections: you can reuse them ad infinitum; arrays are inherently mutable but only in terms of their elements... and here we have no elements to change! As arrays aren't resizable, an empty array is as immutable as an object can be in .NET.

Note that it's often useful to have an empty array instead of a null reference: methods or properties returning collections should almost always return an empty collection rather than a null reference, as it provides consistency and uniformity - rather than making every caller check for nullity. If you want to avoid allocating more than once, you can use:

public static class Arrays<T> {     private static readonly T[] empty = new T[0];      public static readonly T[] Empty { get { return empty; } } } 

Then you can just use:

return Arrays<string>.Empty; 

(or whatever) when you need to use a reference to an empty array of a particular type.

like image 60
Jon Skeet Avatar answered Sep 22 '22 20:09

Jon Skeet