Outputting a Key Value

The power of an associative array is that it uses keys, text or numbers, to reference values. Know the key and you can fetch the value . This “association” works like an array in C, where you know the index or offset for an element. Though with an associative array, the index is a value or string — the key.

For my demonstration, I continue with an phony associative array of strings used in last week’s Lesson. The keys are month names in English with the values their corresponding month names in French. The key() function is passed two arguments: *k a key to match and *a[] the phony-associative array containing the key-value pairs. Here is the function:

/* assumes `char` array */
char *key(char *k, char *a[])
{
    int x = 0;

    /* the loop ends on the NULL */
    while( a[x] )
    {
        /* use strcasecmp() if the library has it */
        if( strcmp(k,a[x])==0 )
            return(a[x+1]);
        x+=2;
    }
    return(NULL);
}

The while loop spins until the end of array a[], which is marked with NULLs. Within the loop, an strcmp() function compares the key passed, *k, with each key item in the array, a[x]. When a match is found, meaning strcmp() returns zero, element a[x+1] is returned. The +1 offset represents the key’s value in the phony-associative array. Otherwise, variable x is increased by two to reference the next key in the phony associative array.

When the array is exhausted, the value NULL is returned.

I could have put the strcmp() function within the while() loop, but extra overhead is required to determine when the a[x] value is NULL. It seems less complicated to me to use value a[x] as the comparison.

Also, if your compiler’s library features the strcasecmp() function, you can use it instead of strcmp(). Though, grammatically speaking, month names in English are capitalized.

Within the main() function, input is requested. The input string is passed to the key() function. The value returned is compared with NULL and appropriate text is output:

int main()
{
    char *months[] =
    {
        "January", "janvier",
        "February", "fevrier",
        "March", "mars",
        "April", "avril",
        "May", "mai",
        "June", "juin",
        "July", "julliet",
        "August", "aout",
        "September", "septembre",
        "October", "octobre",
        "November", "novembre",
        "December", "decembre",
        NULL, NULL
    };
    char a[16];
    char *b;

    printf("Month in English: ");
    /* scanf() doesn't monitor overflow! */
    scanf("%s",a);
    b = key(a,months);
    if( b!=NULL )
        printf("'%s' is '%s' in French\n",a,b);
    else
        printf("'%s' isn't a month name\n",a);

    return(0);
}

I dislike using the scanf() function for any form of input, but it presents a single statement here instead of my having to craft my own input function. Array a[] is fixed to 16 characters (15 text plus the null character), but this limit isn’t tested by the scanf() function. If you release such code into the wild, ensure you use a proper text input function complete with bounds-checking.

Click here to view the full code on GitHub. Here’s a sample run:

Month in English: May
'May' is 'mai' in French

And a sample run with bogus input:

Month in English: Bogus
'Bogus' isn't a month name

By using an associative array, even a phony one in C, I’m able to finally reach the goal I desired in this series’ original post: To create a pair of arrays to translate from English to French.

This phony associative array concept can be expanded further, but not without some modification. Functions can be built to create the array, assigning keys and values. To accomplish this task, it’s better to create a linked list of dictionary structures with key and value members, as was suggested in an earlier comment in this series.

2 thoughts on “Outputting a Key Value

  1. I’m currently researching for an article on obscure data structures and I’ve just found that there’s a thing called a parallel array which is sort of what I was getting at in previous comments. In the Wikipedia article

    https://en.wikipedia.org/wiki/Parallel_array

    they are used for fields of records but could be used for a dictionary.

    Actually what you need here is a sort of two-way dictionary to translate from either language to the other, so each set of values can act as both keys and values. Maybe that exists already. Every time I invent anything I find somebody else got there first.

  2. Neat! Perhaps there is a need for this type of data structure, and a way to address the shortcomings described in the article.

Leave a Reply