我有以下代码:
/* 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;
};当我试图访问元素时,我得到了一个分段错误。谁能告诉我访问这些元素的正确方式是什么?
发布于 2012-01-27 15:56:26
使用此结构:
#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)发布于 2012-01-27 14:51:14
您的malloc()行不正确:
h = ( struct hermes *) malloc ( sizeof ( struct hermes *));应该是:
h = ( struct hermes *) malloc ( sizeof ( struct hermes));卸下sizeof()中的*。否则,你只能为一个指针分配足够的空间,而不是结构本身。
此外,在C中也不需要强制转换。
发布于 2012-01-27 15:02:12
这不是访问元素的问题。这就是你所做的所有正确的事情。
以下是一些错误的地方。首先,您没有为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),所以在这种情况下,如果您不这样做,也没有什么坏处。
https://stackoverflow.com/questions/9029887
复制相似问题