如何访问结构体内部的联合?

发布于 2024-12-29 10:01:01 字数 910 浏览 2 评论 0原文

我有以下代码:

/* 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 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

忆伤 2025-01-05 10:01:01

您的 malloc() 行不正确:

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

应该是:

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

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

另外,C 中不需要强制转换。

Your malloc() line isn't correct:

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

should be:

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

Remove the * in the sizeof(). Otherwise, you're only allocating enough for a pointer rather than the struct itself.

Also, the cast isn't necessary in C.

清晰传感 2025-01-05 10:01:01

使用此结构:

#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)

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)
抠脚大汉 2025-01-05 10:01:01

这不是访问元素的问题。这就是您所做的所有正确的事情。

以下是一些错误的地方。首先,您没有为 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),因此在这种情况下,如果不这样做也不会造成任何损害。

It's not a problem of accessing the elements. That's about all that you are doing correctly.

Here are some of the things that are wrong. First, you aren't allocating enough space for a hermes struct, just enough for a pointer. Then, even if you malloc( sizeof ( struct hermes ) );, the one element (api) is an uninitialized pointer. You can't just follow uninitialized pointers down deep into the data structure, because they will be pointing to who knows where in memory. You first need to allocate something for h->api to point to. Then you need to allocate space for h->api->search_response. If you correct all that, then you are copying a string to ... who knows where? You should use strdup, not strcpy to create a new string, then you should assign the return value to result_code. Also, your union has only one element, so it's kind of pointless (unless there's more to it that you haven't posted).

EDIT Here's one way of initializing 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" );

Note that in a well-behaved program that cleans up after itself, each of these allocations will have to be freed individually as well, in reverse order of the calls to malloc. Since you immediately call exit(0), no harm is done in this case if you don't.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文