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

Character Array Reference

Part of ArraysCategory

Description

Shows how an array can reference another array.

Example

import std.stdio;

void main()
{
    char[] a = new char[20];
    char[] b = a[0..10];
    char[] c = a[10..20];


    a[] = ' ';      /* Fill with spaces so that I can print the array elements. */

    writefln("(before)   a[11]: %s   a[15]: %s   c[1]: %s   c[5]: %s", a[11], a[15], c[1], c[5]);

    b.length = 15;	/* always resized in place because it is sliced
    		           from a[] which has enough memory for 15 chars */
    b[11] = 'x';    /* a[11] and c[1] are also affected */

    writefln("(after)    a[11]: %s   a[15]: %s   c[1]: %s   c[5]: %s", a[11], a[15], c[1], c[5]);

    a.length = 1;
    a.length = 20;	/* no net change to memory layout */

    c.length = 12;	/* always does a copy because c[] is not at the
    		           start of a gc allocation block */
    c[5] = 'y';	   /* does not affect contents of a[] or b[] */

    a.length = 25;	/* may or may not do a copy */
    a[3] = 'z';	   /* may or may not affect b[3] which still overlaps
                          the old a[3] */
}

Output

(before)   a[11]:     a[15]:     c[1]:     c[5]:
(after)    a[11]: x   a[15]:     c[1]: x   c[5]:

Source

Based on the example code from http://www.digitalmars.com/d/arrays.html, "Setting Dynamic Array Length" section.