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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to combine 2 arrays of structs (as a map) into a third array in C

1 Answer

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

#define MAX_SIZE 64

typedef struct {
    char key[16];
    char value[32];
} MapEntry;

MapEntry map1[MAX_SIZE] = {
    {"A", "aaa"},
    {"B", "bbb"}
};
int size1 = 2;

MapEntry map2[MAX_SIZE] = {
    {"C", "ccc"},
    {"B", "XYZ"},  // Overwrites key "B"
    {"B", "XYZ"} 
};
int size2 = 2;

MapEntry combined[MAX_SIZE];
int size_combined = 0;

// Function to find index of a key in combined
int findKeyIndex(const char *key) {
    for (int i = 0; i < size_combined; i++) {
        if (strcmp(combined[i].key, key) == 0)
            return i;
    }
    return -1;
}

void combineMaps() {
    // Copy map1 into combined
    for (int i = 0; i < size1; i++) {
        strcpy(combined[size_combined].key, map1[i].key);
        strcpy(combined[size_combined].value, map1[i].value);
        size_combined++;
    }

    // Merge map2 into combined, overwriting duplicates
    for (int i = 0; i < size2; i++) {
        int index = findKeyIndex(map2[i].key);
        if (index != -1) {
            // Overwrite existing value
            strcpy(combined[index].value, map2[i].value);
        } else {
            // Add new entry
            strcpy(combined[size_combined].key, map2[i].key);
            strcpy(combined[size_combined].value, map2[i].value);
            size_combined++;
        }
    }
}

void printMap(MapEntry map[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%s => %s\n", map[i].key, map[i].value);
    }
}

int main() {
    combineMaps();
    printf("Combined Arrays:\n");
    printMap(combined, size_combined);
    
    return 0;
}




/*
run:

Combined Arrays:
A => aaa
B => XYZ
C => ccc

*/

 



answered Aug 25, 2025 by avibootz

Related questions

3 answers 185 views
1 answer 131 views
2 answers 197 views
2 answers 148 views
3 answers 181 views
2 answers 180 views
...