Array with char-keys

Daniel Keep daniel.keep.lists at gmail.com
Fri May 25 01:34:26 PDT 2007



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.
	
> 	index.readExact(&VFIndex[namet].flags, 1);
> 	index.readExact(&VFIndex[namet].pos, 4);
> 	index.readExact(&VFIndex[namet].size, 4);
> 	writefln("file: ", namet, " in VFS-File: ", VFIndex[namet].VFSfile, " pos: ", VFIndex[namet].pos, " size: ", VFIndex[namet].size);			
> }
> up to this point it seems to work correctly... i hope it isn't too hard to understans... i am reading a file that has informations about in which vfs (virtual file system) the files are and then the name-length, the name, and other informations...
> i want to read them all into the array VFIndex so that i can later get the informations with VFIndex["file1.dat"] and VFIndex["file2.dat"] and so on...
> i think my mistake is at the **-marked line but i am not sure..
> anyone any idea?!?

Out of interest, what language(s) are you coming from?

    -- Daniel

P.S.  Full disclosure: changing .length *can* give you a new string, but
only if the new length doesn't fit into the previously allocated
storage.  So files with the same length or shorter won't get new
storage.  Ones that are larger *might*.

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/



More information about the Digitalmars-d mailing list