views:

46

answers:

3

How would one implement a dynamic associative array that could take any number of mixed indices (integers, strings, or both)?

I aim to simulate structures by providing, for example, people[3].location as syntactical sugar for people[3, "location"]. How would you recommend representing this kind of array internally?

By the way, I am using C, and for portability reasons I can only use the standard libraries.

Thanks for your suggestions!

Edit: Just to clarify, I'm asking how one would implement a dynamic associative array with mixed indices for a programming language interpreter written in C. The interpreter in question is actually Yabasic, but that is not particularly relevant.

Edit: Changed to use [] for array syntax rather than ().

A: 

Use a binary tree like a Red-Black tree or an AVL tree. Wikipedia has some OK information on them both.

EDIT: You can't overload the subscript [] operators in C.

Duracell
Just to clarify, I'm asking how one would implement a dynamic associative array with mixed indices for a *programming language interpreter* written in C.
Thomas Larsen
A: 

Have a look into open source projects that provide such a feature and that are written in C. Come into mind perl and emacs, that both have powerful associative arrays. In perl it is their hash implementation and in emacs lisp their symbol handling. Perhaps you could get some inspiration from there.

Jens Gustedt
A: 

I would probably go for a hash table for the string keys with possibly a vector for the integer keys, both pointing to the same data.

I'm thinking of the way php handles arrays: http://www.php.net/manual/en/language.types.array.php

SpacedMonkey