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

Changes from Version 1 of CharArrayRefExample

Show
Ignore:
Author:
jcc7 (IP: 192.149.244.9)
Timestamp:
04/26/06 16:02:24 (18 years ago)
Comment:

created example

Legend:

Unmodified
Added
Removed
Modified
  • CharArrayRefExample

    v0 v1  
     1= Character Array Reference = 
     2 
     3''Part of'' ArraysCategory 
     4 
     5== Description == 
     6 
     7Shows how an array can reference another array. 
     8 
     9== Example == 
     10 
     11{{{ 
     12#!d 
     13import std.stdio; 
     14 
     15void main() 
     16{ 
     17    char[] a = new char[20]; 
     18    char[] b = a[0..10]; 
     19    char[] c = a[10..20]; 
     20 
     21 
     22    a[] = ' ';      /* Fill with spaces so that I can print the array elements. */ 
     23 
     24    writefln("(before)   a[11]: %s   a[15]: %s   c[1]: %s   c[5]: %s", a[11], a[15], c[1], c[5]); 
     25 
     26    b.length = 15;      /* always resized in place because it is sliced 
     27                           from a[] which has enough memory for 15 chars */ 
     28    b[11] = 'x';    /* a[11] and c[1] are also affected */ 
     29 
     30    writefln("(after)    a[11]: %s   a[15]: %s   c[1]: %s   c[5]: %s", a[11], a[15], c[1], c[5]); 
     31 
     32    a.length = 1; 
     33    a.length = 20;      /* no net change to memory layout */ 
     34 
     35    c.length = 12;      /* always does a copy because c[] is not at the 
     36                           start of a gc allocation block */ 
     37    c[5] = 'y';    /* does not affect contents of a[] or b[] */ 
     38 
     39    a.length = 25;      /* may or may not do a copy */ 
     40    a[3] = 'z';    /* may or may not affect b[3] which still overlaps 
     41                          the old a[3] */ 
     42} 
     43}}} 
     44 
     45 
     46 
     47== Output == 
     48{{{ 
     49(before)   a[11]:     a[15]:     c[1]:     c[5]: 
     50(after)    a[11]: x   a[15]:     c[1]: x   c[5]: 
     51}}} 
     52 
     53== Source == 
     54Based on the example code from http://www.digitalmars.com/d/arrays.html, "Setting Dynamic Array Length" section. 
     55