1

I am trying to write something in c that relates two arrays to each other but I am very novice in c language and I don't want to start off with the wrong path... What I need is something like python's dict and I am thinking of using a struct. Is this the way to go or is there something I'm missing?

Thanks ;)

Stamoulohta
  • 649
  • 1
  • 7
  • 21
  • Can you be more specific? 'Relates two arrays' means nothing. How are you thinking of using a struct? –  Dec 23 '11 at 08:54
  • Sorry, I thought of having two equal length arrays in my struct (say keys and values) and by looking to the index of the key I want, I would know the index of the value... – Stamoulohta Dec 23 '11 at 08:59
  • 1
    If it's sufficient for you to have O(N) lookup cost then you have a good solution. You can sort the elements to improve this to O(logN). You may find there's no need to implement a hashtable (which is more efficient, but much more difficult to code). –  Dec 23 '11 at 09:02
  • I guess you need something like key:value pair? – dicaprio Dec 23 '11 at 09:07
  • You may also want to search for the tag `hashtable` here in SO. – dicaprio Dec 23 '11 at 09:15

3 Answers3

2

I think you are looking for an HashTable. I just googled for an example, but look around I'm sure you will find an implementation example satisfying your needings.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
2

A Python dict and a C struct are very different beasts.

A struct can be thought of as a way to group related variables together, so that they can be passed around as a single unit.

A dict is a mapping from keys to values, where the set of keys is generally not known at compile time. If you need to do something similar in C, your best bet is probably to use a library of standard data structures. These have been discussed in the past: Are there any open source C libraries with common data structures?

There are several standard data structures that can enable one to map keys to values. A hash table is a sensible default choice.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Search for the tag hastable or text implementation in C here in SO and you'll find some examples and also interesting problems and solutions worth reading.

dicaprio
  • 713
  • 2
  • 8
  • 25