C Dictionary Implementation Guide

One common way to implement a dictionary in C language is by using a hash table, as there is no built-in dictionary data structure available. Other options include using arrays or linked lists to achieve a similar functionality.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 100

typedef struct {
    char key[50];
    char value[50];
} KeyValuePair;

typedef struct {
    KeyValuePair data[MAX_SIZE];
    int count;
} Dictionary;

void initialize(Dictionary* dictionary) {
    dictionary->count = 0;
}

void insert(Dictionary* dictionary, const char* key, const char* value) {
    if (dictionary->count >= MAX_SIZE) {
        printf("Dictionary is full.\n");
        return;
    }

    strcpy(dictionary->data[dictionary->count].key, key);
    strcpy(dictionary->data[dictionary->count].value, value);
    dictionary->count++;
}

const char* find(Dictionary* dictionary, const char* key) {
    for (int i = 0; i < dictionary->count; i++) {
        if (strcmp(dictionary->data[i].key, key) == 0) {
            return dictionary->data[i].value;
        }
    }

    return NULL;
}

int main() {
    Dictionary dictionary;
    initialize(&dictionary);

    insert(&dictionary, "apple", "果实");
    insert(&dictionary, "banana", "香蕉");
    insert(&dictionary, "cherry", "樱桃");

    const char* value = find(&dictionary, "banana");
    if (value) {
        printf("The Chinese meaning of 'banana' is '%s'\n", value);
    } else {
        printf("Cannot find the word 'banana'\n");
    }

    return 0;
}

This example demonstrates a simple dictionary data structure implemented using a hash table. The Dictionary structure includes an array of KeyValuePair to store key-value pairs. New key-value pairs can be inserted into the dictionary using the insert function, and the value of a specific key can be found using the find function.

bannerAds