vdenotaris
vdenotaris

Reputation: 13637

Void pointers, type casting and possible code improvements

Considering the code as 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, as expected, generates a warning:

format ‘%lf’ expects argument of type ‘double *’, but argument 3 has type ‘void *’

I am looking for a suggestion to better implement this function and, of course, avoid the warning above.

Elsewhere, considering also the code:

double timestamp;
void *holder;

// some other code...
// response_obj already initialized 
get_value_by_peek_name(response_obj, "timestamp", &holder);
timestamp = *((double *) holder);
printf("- timestamp: %lf\n", timestamp);

Is there a good way to make this code more elegant, without declaring explicitly the void pointer holder but by using directly timestamp to hold the value?

Upvotes: 0

Views: 141

Answers (1)

alk
alk

Reputation: 70903

avoid the warning above.

  1. Define get_value_by_peek_name() to take a void* as last parameter:

    void get_value_by_peek_name(json_object * json_obj, const char * peak_name, void * value)
    
  2. Make sure holder points to a double (or at least to enough memory, which as well is properly aligned to hold a double), then

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

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

Upvotes: 3

Related Questions