Search code examples
cpointersstructunions

How to access union inside structure?


I have the following code:

/* sample.c */ 
    #include<stdio.h> 
    #include<malloc.h> 
    #include<stdlib.h> 
    #include"hermes.h" 
    #include<string.h> 

    int main (){
        struct hermes *h ;
        h = ( struct hermes *) malloc ( sizeof ( struct hermes *));

        strcpy ( h->api->search_response->result_code , "123" );
            printf("VALue : %s\n" , h->api->search_response->result_code );
        return 0; 
    }

/* hermes.h */ 
    struct hermes {

     union  {

          /* search response */
                    struct  {
                            int error_code;
                            char *result_code;
                            char *user_track_id;
                            struct bus_details bd;
                    }*search_response;

        }*api;
    };

I get a segmentation fault when I try to access the elements. Could anyone tell me what is the right way to access these elements?


Solution

  • Use this struct:

    #define MAX 512 /* any number you want*/
    
    struct hermes {
         union  {
    
              /* search response */
                        struct  {
                                int error_code;
                                char result_code[MAX];
                                char user_track_id[MAX];/* can use different sizes too*/
                                struct bus_details bd;
                        }search_response[MAX];/* can use different sizes too*/
    
            }*api;
        };
    

    Or if you want to use your current struct, malloc the pointer element like:

     h->api = malloc((sizeof(int)+sizeof(char)*MAX*2+sizeof(struct bus_details))*MAX)