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,900 questions

51,831 answers

573 users

How to create, initialize, and print key-value pair in C

1 Answer

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

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

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

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

int main() {
    KeyValuePair* keyvalue = create_keyvaluepair(10);
    
    print_keyvaluepair(keyvalue, 10);
    
    free(keyvalue);
    
    return 0;
}



/*
run:

0 83
1 53
2 79
3 14
4 57
5 1
6 59
7 8
8 38
9 87

*/

 



answered Feb 15, 2024 by avibootz

Related questions

...