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

51,772 answers

573 users

How to define and use union within a struct in C

2 Answers

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

struct 
{
    char name[32];
    int age;
    union u_variable 
    {
        int i;
        float f;
        char ch;
    } u;
} st;

int main(void)
{
    strcpy(st.name, "star war 7");
    st.age = 38;
    st.u.i = 100;
    
    printf("st.name = %s\n", st.name);
    printf("st.age = %d\n", st.age);
    printf("st.u.i = %d\n", st.u.i);
    
    st.u.f = 3.14;
    printf("st.u.f = %.2f\n", st.u.f);
            
    return 0;
}


/*
run:
 
st.name = star war 7
st.age = 38
st.u.i = 100
st.u.f = 3.14

*/

 



answered Dec 9, 2015 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

struct DATA
{
    char name[32];
    int age;
    union u_variable 
    {
        int i;
        float f;
        char ch;
    } u;
};

int main(void)
{
    struct DATA st[3];
    
        
    strcpy(st[0].name, "star war 7");
    st[0].age = 38;
    st[0].u.i = 100;
    
    printf("st[0].name = %s\n", st[0].name);
    printf("st[i].age = %d\n", st[0].age);
    printf("st[i].u.i = %d\n", st[0].u.i);
    
    st[0].u.f = 3.14;
    printf("st[0].u.f = %.2f\n", st[0].u.f);
            
    return 0;
}


/*
run:
 
st[0].name = star war 7
st[i].age = 38
st[i].u.i = 100
st[0].u.f = 3.14

*/

 



answered Dec 10, 2015 by avibootz

Related questions

1 answer 147 views
147 views asked Dec 27, 2020 by avibootz
1 answer 134 views
1 answer 175 views
1 answer 117 views
1 answer 147 views
147 views asked Aug 29, 2016 by avibootz
2 answers 133 views
...