Array with char-keys

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Fri May 25 02:17:30 PDT 2007


Charma wrote:
> Daniel Keep Wrote:
> 
>>
>> Charma wrote:
>>> thanks to all..
>>> i have tested it...
>>> seems to work as long as i am writing into the string, but it somehow looks like it is always overriding the same entry...
>>>
>>> i got my class:
>>> class VFIentry
>>> {
>>> 	byte VFSfile;
>>> 	uint pos;
>>> 	uint size;
>>> 	byte flags;
>>> }
>>>
>>> and later in some code i do this:
>>>
>>> VFIentry[char[]] VFIndex; // this is the array
>>>
>>>
>>> byte VFSt;
>>> char[] namet;
>>> while(!index.eof())
>>> {
>>> 	index.readExact(&VFSt, 1);
>>> 	index.readExact(&t, 1);
>> From here...
>>
>>> 	namet.length = t;
>>> 	index.readExact(namet.ptr, t);
>>> 	VFIndex[namet] = new VFIentry; // **
>>> 	VFIndex[namet].VFSfile = VFSt;
>> ...to here is, I think, your problem.
>>
>> Strings in D are arrays, and arrays are reference types.  So what's
>> happening here is that you're reading in the file's name, storing it
>> away... and then *overwriting it* on the next file.
>>
>> What you need to do is copy the buffer if you plan on re-using it, or
>> simply create a new buffer in the first place.  Since you're actively
>> using namet in several places, I'd replace:
>>
>>   namet.length = t;
>>
>> with:
>>
>>   namet = new char[t];
>>
>> And it should work from there.
>> 	
[snip]
> 
> thanks a lot! my problem is solved, but to be honest i am not 100% sure why... 
> maybe you could explain that again?!? (sorry about that... english isn't my native language)

A dynamic array (let's say T[]) in D is best thought of as a struct { 
size_t length; T* ptr; }. When you make a copy of it (which happens when 
you use it as an AA key, for example) this struct is copied, not the 
data the "ptr" member points to.
What you were doing was changing the data it points to while it was 
still being used as an AA key...

> What I don't understand is why i still need the old name?!

Because the data is still referenced by the AA key.

> once i have saved it in VFIndex, i can override it, right?

You shouldn't overwrite[1] array data once the array reference is 
"saved" into an AA key.

[1] (You can't override it ;) )

> it is not needed anymore since it is saved in VFIndex, isn't it?

It *is* needed since only the _reference_ is "saved" into the AA.



More information about the Digitalmars-d mailing list