Search code examples
cpointersglibdereference

glib GHashtable dereference gpointer


Hi This issues related to GLib, gpointer.

I create a value with gpointer type.

    gpointer        keys;

I called a function

insert_data(gpointer key);

I passed the integer pointer to this function like that.

int* p = malloc(sizeof(int));
*p = 1;
// gpointer is void* pointer, I cast it to integer type pointer here.
insert_data(p);

Inside the function I want to see the value of p.

printf("%d\n", (int*)p);

It outputs some very large number.From my side it is 296304, no the actually value 1. I want to know how to dereference a pointer like gpointer.

For integer 32 bits pointer, char* pointer, how to dereference them?

Thanks


Solution

  • You are attempting to print the pointer itself. Technically, this is undefined behaviour since you are using the wrong format specifier to print a pointer. What you observe is the integer interpretation of the pointer p.

    Change

    printf("%d\n", (int*)p);
    

    to

    printf("%d\n", *(int*)p);
    

    Or you can do:

    insert_data(gpointer ptr)
    {
      int *p = ptr;
      printf("%d\n", *p);
      ...
    }