So I a function which returns a pointer to a struct (parse_files_result_t*
). This struct contains a union:
struct parse_files_result_t{
result_tag tag;
union {
struct parse_file_error_t *err_ptr;
struct parse_file_response_t *ok_ptr;
} data;
};
And I wanted to use the union to return an *err_ptr
or an *ok_ptr
based on the calculations in the function.
所以我写了下面的代码:
parse_files_result_t* result = (parse_files_result_t*)malloc(sizeof (parse_files_result_t));
if (success) {
parse_file_response_t response = //data
*result = parse_file_response_t{result_tag::Ok, result->data.ok_ptr = &response};
return result;
} else {
parse_file_error_t errorresponse = //data
*result = parse_files_result_t{{result_tag::Err}, {result->data.err_ptr = &errorresponse}};
return result;
}
So far so good. The else
part, where a parse_file_error_t
gets returned, works fine because the parse_file_error_t
is the first part of the union. In the if
part, I want to return only the parse_file_response_t
. Because this is the second "part" of the union, I get this error:
错误:初始化时无法将“ parse_file_response_t *”转换为“ parse_file_error_t *”
Even though I wrote result->data.ok_ptr
, my compiler tries to put the parse_file_response_t response
into the parse_file_error_t
part of the union.
我怎样才能解决这个问题?
谢谢你的帮助!