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.

  1. define get_value_by_peek_name() take void* last parameter:

    void get_value_by_peek_name(json_object * json_obj, const char * peak_name, void * value) 
  2. make sure holder points double (or @ least enough memory, aligned hold double), then

  3. properly cast pointer in call sscanf() before dereferencing it:

    sscanf(json_object_to_json_string(value_obj), "%lf", *((double**)value)); 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -