简体   繁体   中英

Associative array in C

In php I can crate a associative array like

$my_arr = array('a' => 'Apple', 'b' => 'Ball', 'c' => 'Cat');

Is it possible to create a associative array in C

You may think it is duplicate question for Associative arrays in C But I can't found what I want.

There's no prebuilt utility in standard C to accomplish this task. Your best shot is to try to implement a red-black tree (or an hash table for non ordered associative containers) on your own.

If you have the luck to work with C++, on the other hand, you can use std::map . Here's an example for std::map :

std::map<char, std::string> map;
map['a'] = "Apple";
map['b'] = "Ball";
map['c'] = "Cat";

Live example

Really robust and simple way to do it is to have a struct with key and value fields. Lets call it pair (name derived from C++ class of the same name and purpose). Also you should think of the types you want have for the pair fields. I give an example as char to string values as your php example. But in order to use different types you must use void*, but that will result in a very complicated and probably bug prone implementation.

Something like

struct
{
    char key;
    char* value;
}pair;

struct pair map[size];

pair assocation;
assocation.key = 'a';
assocation.value = "Apple"; // Be sure to allocate the C strings so that you do not introduce memory leak or data corruption, same for void*. This here is just an hack.

map[0] = assocation;  

// Later in your algorithms and parsers you just access it as an value in array.  
pair aPair = map[1];
char aKey = aPair.key;
char* aValue = aPair.value;

When you want a linked list like associative array, then add one more field to a struct:

void* nextPair;  

With that you can allocate you key-value pairs everywhere and do not need to contain them in a single array.

As others have said, C is too low-level to have a built-in associative array type. Probably the closest you can get to it is to use a third party library such as http://svn.freebsd.org/base/head/sys/sys/tree.h , documented in http://www.freebsd.org/cgi/man.cgi?tree or http://ivoras.sharanet.org/freebsd/usetree.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM