Associative array key changes

Erik Rasmussen i_am_erik at yahoo.com
Mon Mar 20 06:50:23 PST 2006


I've read this 
(http://www.digitalmars.com/d/archives/digitalmars/D/12062.html), but 
there's something I don't understand.  Check out the following code:

---
import std.stdio;

int main(char[][] args)
{
   int[char[]] table;

   char[] key = "hello".dup;
   table[key] = 4;
   table["dude"] = 69;

   key[2] = 'r';
//  table["herlo"] = 71;

   writefln("size: %d", table.length);
   foreach(char[] k; table.keys)
   {
     writef("'%s'\t-->\t", k);
     int* value = k in table;
     if(value is null)
       writefln("null");
     else
       writefln(*value);
   }
   return 0;
}
---

If you run this, you get:
---
size: 2
'dude'  -->     69
'herlo' -->     null
---

This is almost what I would expect.  I might like table["herlo"] to be 
4, but I can maybe understand why it wouldn't be.

But then!  If you uncomment the commented line, you get this:

---
size: 3
'herlo' -->     71
'dude'  -->     69
'herlo' -->     71
---

Why are there two identical keys???  Why is the size 3?

Maybe the lesson here is just that you should never change the values of 
keys inside associative arrays because the behavior will be hard to 
predict...

Any insights out there?

Cheers,
Erik



More information about the Digitalmars-d-learn mailing list