Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much information do array variables share?

How much information is copied/shared when I assign one array variable to another array variable?

int[] a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
int[] b = a;
a[0] = 42;
writefln("%s %s", a[0], b[0]);   // 42 42

Apparently, a and b share the same payload, because 42 is printed twice.

a ~= 10;
writefln("%s %s", a.length, b.length);   // 11 10

Appending to a does not change b, so the length does not seem to part of the payload?

b = a;
a ~= 11;
b ~= 42;
writefln("%s %s", a[11], b[11]);   // 11 42

Could a conforming D implementation also print 42 42? Could b ~= 42 overwrite the 11 inside a?

When exactly are a and b detached from each other? Is D performing some COW in the background?

like image 448
fredoverflow Avatar asked Jan 09 '12 15:01

fredoverflow


People also ask

How much memory does an array occupy?

If the array is a character array, then its elements will occupy 1 byte of memory each. If it is a float array then its elements will occupy 8 bytes of memory each.

What information does an array store?

Arrays are classified as Homogeneous Data Structures because they store elements of the same type. They can store numbers, strings, boolean values (true and false), characters, objects, and so on. But once you define the type of values that your array will store, all its elements must be of that same type.

Why is an array more useful than a single variable?

Arrays are used when there is a need to use many variables of the same type. It can be defined as a sequence of objects which are of the same data type. It is used to store a collection of data, and it is more useful to think of an array as a collection of variables of the same type.

How helpful are arrays in keeping information?

Arrays store multiple data of similar types with the same name. It allows random access to elements. As the array is of fixed size and stored in contiguous memory locations there is no memory shortage or overflow. It is helpful to store any type of data with a fixed size.


1 Answers

"Arrays" in D don't really exist.

Slices do.

Slices are just a pointer and a length. So when you assign them to each other, the pointer and the length get copied. If you modify the target data, then it'll be visible in all instances of the slices -- but if you enlarge one slice, the other one will still be using its old length.

You normally can't "shrink" the actual length of the array in memory (although you can certainly reduce the slice's length, so it 'sees' less data), so that doesn't cause issues.

Hope that explains what's going on.

like image 169
user541686 Avatar answered Sep 23 '22 03:09

user541686