Moving structs containing strings ...

Derek Parnell derek at psych.ward
Mon Apr 24 04:43:56 PDT 2006


On Mon, 24 Apr 2006 20:19:43 +1000, Bob W <nospam at aol.com> wrote:

>
> "Derek Parnell" <derek at psych.ward> wrote in message
> news:c7u4nwvom7ca$.o0vru71wqxwe.dlg at 40tude.net...
>>
>> Another solution is to recalculate the addresses of the id strings after
>> changing the length ...
>>
>>  arr=arr[0..2];   // adjust length
>>  foreach( inout Sc s; arr)
>>      s.id = s.idz[0..s.id.length];
>>
>
> I'll gladly accept this as a solution, because it will
> utilize existing strings within the structs-array.
>
> The workaround you have posted earlier allocates
> memory and duplicates strings one by one. That is
> something I would not want to try in real-world
> applications due to obvious reasons.
>
> Thanks for your input.

However, there's a typo in it. Here is a fuller test of it ...

//------------------------
import std.stdio;

alias std.stdio.writefln wrl;

void AssignIdAddr(Sc[] pArr)
{
   foreach( inout Sc s; pArr)
       s.id = s.idz[0 .. $];
}

void DisplayArray(Sc[] pArr, char[] pMsg)
{
   wrl("\n%s...", pMsg);
   foreach (uint i, Sc s; pArr)
     wrl("arr[%d] - val:%d, id:'%s'", i, s.val, s.id);
}

struct Sc { uint val;  char[2] idz;  char[] id;
             void opCall(char[] z, uint v)
              {
                  idz[]=z;
                  val = v;
             }
         }

Sc[] arr;

void main()
{

   // init array
   arr.length = arr.length + 1; arr[$-1]("ab", 101);
   arr.length = arr.length + 1; arr[$-1]("cd", 102);
   arr.length = arr.length + 1; arr[$-1]("ef", 103);
   arr.length = arr.length + 1; arr[$-1]("gh", 104);
   AssignIdAddr(arr);

   DisplayArray(arr, "Original");

   // delete first item
   for( uint i = 0; (i+1) < arr.length; i++)
     arr[i]=arr[i+1];
   arr.length = arr.length - 1;   // adjust length
   AssignIdAddr(arr);

   DisplayArray(arr, "Updated");
}
//------------------------

-- 
Derek Parnell
Melbourne, Australia



More information about the Digitalmars-d-bugs mailing list