How to create an associative-like array (key-value array) in C

3 Answers

0 votes
// Array of structs 
// The most common "associative array" pattern in C.

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

typedef struct {
    const char *key;
    int value;
} Pair;

int main() {
    Pair items[] = {
        {"apple", 5},
        {"banana", 10},
        {"orange", 15},
        {"strawberries", 20}
    };
    int size = sizeof(items) / sizeof(items[0]);

    const char *search = "orange";

    for (int i = 0; i < size; i++) {
        if (strcmp(items[i].key, search) == 0) {
            printf("Found: %s = %d\n", items[i].key, items[i].value);
        }
    }
}



/*
run:

Found: orange = 15

*/

 



answered Mar 21 by avibootz
edited Mar 21 by avibootz
0 votes
// Array of structs 
// The most common “associative array” pattern in C.

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

typedef struct {
    const char *key;
    int value;
} Pair;

int cmp(const void *a, const void *b) {
    return strcmp(((Pair*)a)->key, ((Pair*)b)->key);
}

int main() {
    Pair items[] = {
        {"apple", 5},
        {"banana", 10},
        {"orange", 15},
        {"strawberries", 20}
    };
    int size = sizeof(items) / sizeof(items[0]);

    Pair key = {"orange", 0};
    Pair *found = bsearch(&key, items, size, sizeof(Pair), cmp);

    if (found)
        printf("Found: %s = %d\n", found->key, found->value);
}



/*
run:

Found: orange = 15

*/

 



answered Mar 21 by avibootz
0 votes
// Array of structs 
// The most common “associative array” pattern in C.

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

typedef struct {
    const char *key;
    int value;
} Pair;

int cmp(const void *a, const void *b) {
    return strcmp(((Pair*)a)->key, ((Pair*)b)->key);
}

int main() {
    Pair items[] = {
        {"banana", 10},
        {"apple", 5},
        {"satrawberries", 20},
        {"orange", 15}
    };
    int size = sizeof(items) / sizeof(items[0]);

    qsort(items, size, sizeof(Pair), cmp);

    for (int i = 0; i < size; i++) {
        printf("Found: %s = %d\n", items[i].key, items[i].value);
    }
}


/*
run:

Found: apple = 5
Found: banana = 10
Found: orange = 15
Found: satrawberries = 20

*/

 



answered Mar 21 by avibootz
...