2012-01-27 105 views
1

我有以下代码:如何访问union内部结构?

/* 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; 
    }; 

我得到一个分段错误,当我尝试访问的元素。谁能告诉我什么是访问这些元素的正确方法?

+0

你有一个struct工会的内部结构的内部。也许这是我在C方面的经验不足,但我不知道这个结构可能有什么用处。这里有什么意义? – 2012-01-27 06:52:12

回答

1

使用此结构:

#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; 
    }; 

或者,如果你想用你的当前结构,MALLOC像指针元素:

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

malloc()线是不正确的:

h = (struct hermes *) malloc (sizeof (struct hermes *)); 

应该是:

h = (struct hermes *) malloc (sizeof (struct hermes)); 

sizeof()删除*。否则,你只能为指针分配足够的空间,而不是结构本身。

此外,铸造是在不C.

+0

或者'h = malloc(sizeof * h);' – cnicutar 2012-01-27 06:52:05

+0

仍然结果相同 – abubacker 2012-01-27 06:57:23

+1

您还需要初始化结构中的指针。由于你的代码是现在,'h-> api'是一个悬挂指针。所以当你尝试尊重它的时候,它会发生seg-fault。 – Mysticial 2012-01-27 07:00:07

1

必要这不是访问的元件的问题。这就是你正在做的所有事情。

这是一些错误的东西。首先,你没有为一个hermes结构分配足够的空间,对于一个指针来说就足够了。然后,即使你malloc(sizeof (struct hermes));,一个元素(api)是一个未初始化的指针。你不能仅仅追踪未初始化的指针到数据结构中,因为它们会指向谁知道内存中的哪个位置。您首先需要分配一些用于h->api的指向。然后你需要为h->api->search_response分配空间。如果你纠正了这一切,那么你正在复制一个字符串......谁知道在哪里?您应该使用strdup而不是strcpy来创建一个新字符串,那么您应该将返回值分配给result_code。此外,你的工会只有一个元素,所以这是毫无意义的(除非你还没有发布更多的内容)。

编辑这里的初始化h的一种方式:

h = malloc(sizeof(struct hermes)); 
h->api = malloc(sizeof(*h->api)); 
h->api->search_response = malloc(sizeof(h->api->search_response)); 
h->api->search_response->result_code = strdup("123"); 

注意,在一个乖巧的程序,经过自身清理,这些拨款将不得不单独释放以及,在反向拨打malloc的订单。由于您立即致电exit(0),如果您不这样做,在这种情况下不会造成伤害。

+0

你可以解释如何分配内存给h-> api和h-> api-> search_response – abubacker 2012-01-27 07:05:35

+0

@abubacker - 我添加到我的答案 – 2012-01-27 14:00:35