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

51,776 answers

573 users

How to allocate an array of 3 different structures and use the structs by name in C

1 Answer

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

struct A {
    char type;
    int valueint;
};
struct B {
    char type;
    double valuedouble;
};
struct C {
    char type;
    char valuechar;
};

void* createArray(int size);
void freeArray(void** array);

int main()
{
    int size = 3;
    void** array = createArray(size);
    
    for (int i = 0; i < size; i++)
        switch (*(char*)array[i]) {
        case 'A':
            printf("%d\n", ((struct A*)array[i])->valueint);
            break;
        case 'B':
            printf("%lf\n", ((struct B*)array[i])->valuedouble);
            break;
        case 'C':
            printf("%c\n", ((struct C*)array[i])->valuechar);
            break;
        }

    freeArray(array, size);

    return 0;
}

void* createArray(int size) {
    void** array = malloc(sizeof(void*) * size);

    struct A* a = malloc(sizeof(struct A));
    struct B* b = malloc(sizeof(struct B));
    struct C* c = malloc(sizeof(struct C));

    a->type = 'A';
    a->valueint = 90348;
    b->type = 'B';
    b->valuedouble = 8493.175;
    c->type = 'C';
    c->valuechar = 'z';

    array[0] = a;
    array[1] = b;
    array[2] = c;

    return array;
}

void freeArray(void** array, int size) {
    for (int i = 0; i < size; i++) {
        free(array[i]);
    }

    free(array);
}




/*
run:

90348
8493.175000
z

*/

 



answered Jun 9, 2024 by avibootz
...