Moving structs containing strings ...

Bob W nospam at
Sun Apr 23 15:44:57 PDT 2006

After moving structs containing char[n] arrays
and char[] strings, the latter can point to the
wrong string.

This is a sample program producing the


// test - array struct quirks

// This program demonstrates an unexpected
// D 'feature':
// When members of an array of structs are copied
// from higher to lower array indices, some char[]
// vars of the resulting structs are pointing to
// wrong string locations (dmd 0.154).

import std.stdio, std.string;

alias writefln wrl;  alias writef wr;  alias toString tS;

struct Sc { uint val;  char[3] idz;  char[] id; }

Sc[] arr;

int main() {

  // allocate array space and init array

  with (arr[0]) { idz[]="ab\0";  id=idz[0..2];  val=101; }
  with (arr[1]) { idz[]="cd\0";  id=idz[0..2];  val=102; }
  with (arr[2]) { idz[]="ef\0";  id=idz[0..2];  val=103; }

  // display original

  wrl();  wrl("The original array:");
  foreach (uint x, Sc v; arr)
    wrl("arr[%d] - val:%d, id:'%s'", x,v.val,;

  // ####### this is the trouble spot: #######
  // delete arr[0] by moving arr[1] and arr[2]

  arr[0]=arr[1];  arr[1]=arr[2];
  arr=arr[0..2];   // adjust length

  // diplay 'expected' and 'actual'

  wrl();  wrl("Reduced array should look like this:");
  foreach (uint x, Sc v; arr)
    wrl("arr[%d] - val:%d, id:'%s'", x,v.val,tS(v.idz));

  wrl();  wrl("But it actually looks like that:");
  foreach (uint x, Sc v; arr)
    wrl("arr[%d] - val:%d, id:'%s'", x,v.val,;

  return 0;


Output of the above example:

    The original array:
    arr[0] - val:101, id:'ab'
    arr[1] - val:102, id:'cd'
    arr[2] - val:103, id:'ef'

    Reduced array should look like this:
    arr[0] - val:102, id:'cd'
    arr[1] - val:103, id:'ef'

    But it actually looks like that:
    arr[0] - val:102, id:'ef'      <<<<
    arr[1] - val:103, id:'ef'

More information about the Digitalmars-d-bugs mailing list