2012-01-27 100 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