Search code examples
clistfloating-pointglib

How to add a float to a GList in C?


There is a great C lib called GLib. https://docs.gtk.org/glib/index.html I use and love this. There is a structure in it called GList which is a dinamically growing structure (like a vector). With the g_list_append(GList* list, gpointer* pointer) function I can add new elements to this but there is a problem. If I want to add an Integer I can use the GINT_TO_POINTER macro but there is no GFLOAT_TO_POINTER (but gfloat is a type in glib). I don't want to allocate memory for a float. How can I add one to a GList?

#include <stdio.h>
#include "glib.h"
#include <stdbool.h>

int main() {

        int num = 10;
        gchar* str = g_strdup("Hello");
        GList* list_name = NULL;

        list_name = g_list_append(list_name, GINT_TO_POINTER (4 + num * 3));
        list_name = g_list_append(list_name, "Hello");
        list_name = g_list_append(list_name, str);
        list_name = g_list_append(list_name, GINT_TO_POINTER(num));
        list_name = g_list_append(list_name, GINT_TO_POINTER((int)true));
        list_name = g_list_append(list_name, GINT_TO_POINTER((int)false));

        printf("%d\n", *(int*)(g_list_nth(list_name, 0)));
        printf("%s\n", (gchar*)g_list_nth(list_name, 1)->data);
        printf("%s\n", (gchar*)g_list_nth(list_name, 2)->data);
        printf("%d\n", *(int*)(g_list_nth(list_name, 3)));
        printf("%d\n", *(int*)(g_list_nth(list_name, 4)));
        printf("%d\n", *(int*)(g_list_nth(list_name, 5)));

        g_free(str);
        g_list_free(list_name);

        return 0;
}
~ 

This is how I add int, bool or string to a glist but I don't know how should I add float into the list.


Solution

  • I suspect the reason there is no GFLOAT_TO_POINTER macro is because it's not guaranteed on all the platforms GLib supports that a float is the same number of bits or smaller than a pointer. (See Ghashtable storing double)

    Although, looking at your code sample, it seems like you might be better off using a struct, since it looks like your list is fixed-size and you expect certain types at certain indices. Something like this:

    struct Name {
       int number1;
       const char *static_str;
       char *str;
       int number2;
       bool b1 : 1;
       bool b2 : 1;
    }
    
    // ...
    
    int num = 10;
    char *str = g_strdup("Hello");
    struct Name *name = g_new0(struct Name, 1);
    
    name->number1 = 4 + num * 3;
    name->static_str = "Hello";
    name->str = str;
    name->number2 = num;
    name->b1 = true;
    name->b2 = false;
    
    g_free(name);
    g_free(str);