Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to create a key-value pair with random string as key and random int as value in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct {
    char* key;
    int value;
} KeyValuePair;

static char *generate_random_string(char str[], size_t strsize) {
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    if (strsize) {
        --strsize;
        for (size_t i = 0; i < strsize; i++) {
            int index = rand() % (int)(sizeof charset - 1);
            str[i] = charset[index];
        }
        str[strsize] = '\0';
    }
    return str;
}

KeyValuePair* create_keyvaluepair(int keyvaluepair_size, char str[], int strsize) {
    KeyValuePair* keyvalue = (KeyValuePair*)malloc(keyvaluepair_size * sizeof(KeyValuePair));
    srand((unsigned int)time(NULL));
    
    for (int i = 0; i < keyvaluepair_size; i++) {
        generate_random_string(str, strsize);
        keyvalue[i].key = strdup(str); 
        keyvalue[i].value = (rand() % 100) + 1;
    }
    
    return keyvalue;
}

void print_keyvaluepair(KeyValuePair* keyvalue, int size) {
    for (int i = 0; i < size; i++) {
        printf("%s %d\n", keyvalue[i].key, keyvalue[i].value);
    }
}

int main() {
    char str[7] = "";
    int keyvaluepair_size = 10;
    KeyValuePair* keyvalue = create_keyvaluepair(keyvaluepair_size, str, 7);

    print_keyvaluepair(keyvalue, 10);
    
    for (int i = 0; i < keyvaluepair_size; i++) {
        free(keyvalue[i].key);
    }
    free(keyvalue);
    
    return 0;
}



/*
run:

QBMPEp 98
YwprHn 54
MWgsFP 63
JzbaeD 2
HlUZMi 46
SZgRvX 1
ElDrJK 40
pbzABA 11
hFyPQU 93
ecHXbO 89

*/

 



answered Feb 15, 2024 by avibootz

Related questions

...