| 1 | = Static vs dynamic arrays = |
---|
| 2 | |
---|
| 3 | ''Part of'' ArraysCategory |
---|
| 4 | |
---|
| 5 | == Description == |
---|
| 6 | |
---|
| 7 | Shows the use of static and dynamic arrays, when references are copied and duplication is needed. |
---|
| 8 | |
---|
| 9 | == Example == |
---|
| 10 | |
---|
| 11 | {{{ |
---|
| 12 | #!d |
---|
| 13 | import std.c.stdio; |
---|
| 14 | import std.string; |
---|
| 15 | |
---|
| 16 | int main(char[][] args) |
---|
| 17 | { |
---|
| 18 | int[] a = new int[4]; |
---|
| 19 | static int[4] a1 = [10, 20, 30, 40]; |
---|
| 20 | int[4] b, c; |
---|
| 21 | int[] d, e; |
---|
| 22 | |
---|
| 23 | // initialize the vector a with the values from a1 (i = 0..2, j = a1[0] .. a1[2]) |
---|
| 24 | foreach (int i, int j; a1) |
---|
| 25 | a[i] = j / 10; |
---|
| 26 | printf("a1[2] = %d\n", a1[2]); |
---|
| 27 | // copy the vector a1 in the vector b |
---|
| 28 | b[] = a1; |
---|
| 29 | printf("\tb[2] = %d\n", b[2]); |
---|
| 30 | // duplicate the vector a1 in the vector b (not needed for static arrays) |
---|
| 31 | c[] = a1.dup; |
---|
| 32 | printf("\tc[2] = %d\n", c[2]); |
---|
| 33 | printf("a[2] = %d\n", a[2]); |
---|
| 34 | // copy the vector a in the vector c (d is dynamic, so only the reference is copied) |
---|
| 35 | d = a[]; |
---|
| 36 | printf("\td[2] = %d\n", d[2]); |
---|
| 37 | // duplicate the vector a in the vector c (in this case it makes difference) |
---|
| 38 | e = a[].dup; |
---|
| 39 | printf("\te[2] = %d\n", e[2]); |
---|
| 40 | // now a1[2] is modified |
---|
| 41 | a1[2] = 0; |
---|
| 42 | |
---|
| 43 | printf("a1[2] = %d\n", a1[2]); |
---|
| 44 | // b is not modified |
---|
| 45 | printf("\tb[2] = %d\n", b[2]); |
---|
| 46 | // neither is c |
---|
| 47 | printf("\tc[2] = %d\n", c[2]); |
---|
| 48 | // now a[2] is modified |
---|
| 49 | a[2] = 0; |
---|
| 50 | |
---|
| 51 | printf("a[2] = %d\n", a[2]); |
---|
| 52 | // d IS modified, because it is just a reference |
---|
| 53 | printf("\td[2] = %d\n", d[2]); |
---|
| 54 | // e IS NOT modified, because it is a copy |
---|
| 55 | printf("\te[2] = %d\n", e[2]); |
---|
| 56 | return 0; |
---|
| 57 | } |
---|
| 58 | }}} |
---|
| 59 | |
---|
| 60 | == Source == |
---|
| 61 | |
---|
| 62 | || Link || http://www.dsource.org/tutorials/index.php?show_example=149 || |
---|
| 63 | || Posted by || Anonymous || |