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;
static int a1 = [10, 20, 30, 40];
int b, c;
int[] d, e;

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

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

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

## Source

 Link http://www.dsource.org/tutorials/index.php?show_example=149 Posted by Anonymous