c - Void pointers, type casting and possible code improvements -
considering code follows:
void get_value_by_peek_name(json_object *json_obj, const char *peak_name, void **value) { json_object *value_obj; if (json_object_object_get_ex(json_obj, peak_name, &value_obj)) if (json_object_is_type(value_obj, json_type_double)) sscanf(json_object_to_json_string(value_obj), "%lf", *value); }
this implementation, expected, generates warning:
format ‘%lf’ expects argument of type ‘double *’, argument 3 has type ‘void *’
i looking suggestion better implement function and, of course, avoid warning above.
elsewhere, considering code:
double timestamp; void *holder; // other code... // response_obj initialized get_value_by_peek_name(response_obj, "timestamp", &holder); timestamp = *((double *) holder); printf("- timestamp: %lf\n", timestamp);
is there way make code more elegant, without declaring explicitly void pointer holder
using directly timestamp
hold value?
avoid warning above.
define
get_value_by_peek_name()
takevoid*
last parameter:void get_value_by_peek_name(json_object * json_obj, const char * peak_name, void * value)
make sure
holder
pointsdouble
(or @ least enough memory, aligned holddouble
), thenproperly cast pointer in call
sscanf()
before dereferencing it:sscanf(json_object_to_json_string(value_obj), "%lf", *((double**)value));
Comments
Post a Comment