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 create an array with different data types elements in C

1 Answer

0 votes
#include <stdio.h>

typedef struct {
    int i_nt;
} A;

typedef struct {
    double d_ouble;
} B;

typedef struct {
    char s_tring[32];
} C;

typedef enum {
    TypeAint,
    TypeBdouble,
    TypeCstring,
} type;

typedef struct {
    type type;
    union { A* i_nt; B* d_ouble; C* s_tring; } typesunion;
} AllTypes;

void foreach(AllTypes* alltypes, void (*fnptr)(TypedPointer)) {
    while (alltypes->typesunion.i_nt) {
        fnptr(*alltypes);
        ++alltypes;
    }
}

void print_value(AllTypes at) {
    switch (at.type) {
        case TypeAint: printf("A int: %d\n", at.typesunion.i_nt->i_nt); break;
        case TypeBdouble: printf("B double: %f\n", at.typesunion.d_ouble->d_ouble); break;
        case TypeCstring: printf("C string: %s\n", at.typesunion.s_tring->s_tring); break;
    }
}

int main()
{
    A a = { .i_nt = 96 };
    B b = { .d_ouble = 3.14 };
    C c = { .s_tring = "C Programing" };

    AllTypes arrOfTypes[] = { // array with different data types
        {.type = TypeAint,    .typesunion.i_nt = &a },
        {.type = TypeBdouble, .typesunion.d_ouble = &b },
        {.type = TypeCstring, .typesunion.s_tring = &c },
        {.type = 0,           .typesunion.i_nt = 0} }; // end foreach while loop

    foreach(arrOfTypes, print_value);

    return 0;
}




/*
run:

A int: 96
B double: 3.140000
C string: C Programing

*/

 



answered May 22, 2024 by avibootz
edited May 22, 2024 by avibootz

Related questions

1 answer 139 views
2 answers 154 views
1 answer 137 views
1 answer 146 views
2 answers 176 views
...