Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

# Static vs dynamic arrays

Part of ArraysCategory

## Description

Shows the use of static and dynamic arrays, when references are copied and duplication is needed.

## Example

```import std.c.stdio;
import std.string;

int main(char[][] args)
{
int[] a = new int[4];
static int[4] a1 = [10, 20, 30, 40];
int[4] b, c;
int[] d, e;

// initialize the vector a with the values from a1 (i = 0..2, j = a1[0] .. a1[2])
foreach (int i, int j; a1)
a[i] = j / 10;
printf("a1[2] = %d\n", a1[2]);
// copy the vector a1 in the vector b
b[] = a1;
printf("\tb[2] = %d\n", b[2]);
// duplicate the vector a1 in the vector b (not needed for static arrays)
c[] = a1.dup;
printf("\tc[2] = %d\n", c[2]);
printf("a[2] = %d\n", a[2]);
// copy the vector a in the vector c (d is dynamic, so only the reference is copied)
d = a[];
printf("\td[2] = %d\n", d[2]);
// duplicate the vector a in the vector c (in this case it makes difference)
e = a[].dup;
printf("\te[2] = %d\n", e[2]);
// now a1[2] is modified
a1[2] = 0;

printf("a1[2] = %d\n", a1[2]);
// b is not modified
printf("\tb[2] = %d\n", b[2]);
// neither is c
printf("\tc[2] = %d\n", c[2]);
// now a[2] is modified
a[2] = 0;

printf("a[2] = %d\n", a[2]);
// d IS modified, because it is just a reference
printf("\td[2] = %d\n", d[2]);
// e IS NOT modified, because it is a copy
printf("\te[2] = %d\n", e[2]);
return 0;
}
```