【问题标题】:How can you add an array to a GSList without a variable?如何在没有变量的情况下将数组添加到 GSList?
【发布时间】:2011-05-02 12:58:25
【问题描述】:

我正在使用类似的东西,但是它会抛出错误。

我只是将数组放在一个变量中并以这种方式传递它,但我正在查看近 500 行,例如无模式数据。 (所以我不能使用循环)

此外,使用 GSList 的全部意义在于避免锯齿状数组的限制

list43333 = g_slist_append(list43333,{11,12,13,14,15,17,18,20,22,25,30});

编辑: 使用 `(int[]) 进行强制转换:

csgtk.h:14: warning: data definition has no type or storage class
csgtk.h:14: warning: type defaults to ‘int’ in declaration of ‘list43333’
csgtk.h:14: error: conflicting types for ‘list43333’
csgtk.h:12: note: previous definition of ‘list43333’ was here
csgtk.h:14: warning: passing argument 1 of ‘g_slist_append’ makes pointer from integer without a cast
/usr/include/glib-2.0/glib/gslist.h:52: note: expected ‘struct GSList *’ but argument is of type ‘int’
csgtk.h:14: warning: initialization makes integer from pointer without a cast
csgtk.h:14: error: initializer element is not constant

编辑:文字复制粘贴以显示它没有超出范围(注意,这是在 .h 文件的顶层):

GSList * list43333 = NULL;
list43333 = g_slist_prepend(list43333,(int[]){});

主文件

#include "csgtk.h"

GHashTable * widgetbuffer;
[...]

【问题讨论】:

    标签: c arrays glib singly-linked-list


    【解决方案1】:

    问题是编译器不知道你的数组的类型是什么,所以这样的事情应该可以工作。

    list43333 = g_slist_append(list43333,(int[]){11,12,13,14,15});
    

    但是您应该考虑如何执行此操作,最好创建一个静态常量数组并将其添加到您的GSList,因为在这里您将遇到 O(n²) 类型的运行时间,因为它必须遍历每个追加的列表。

    【讨论】:

    • 但是如果我添加了一个数组,那不就意味着它最终会出现在同一个 GSlist 项中吗?
    • 我可以使用g_slist_prepend() 然后g_slist_reverse() 来解决性能问题,但我仍然无法运行它。
    • 回应您的第一条评论,是的,您是对的,我没想到,是的,您可能应该执行 'g_slist_prepend()` 位。
    • 新警告看起来你没有在任何地方声明list43333,所以它默认为int...
    • 但我有:GSList * list43333 = NULL; 根据参考资料(以及我已经在工作的一些代码正是这样做的)这是初始化 GSList 的正确方法......我不知道是什么错了。
    【解决方案2】:

    刚刚尝试了同样的事情,它的工作原理。 Debian 不稳定 amd64 上的 gcc 4.7.1。顺便说一句,(int []){1, 2, 3} 是 ISO C99 复合文字。

    #include <glib.h>
    
    int main()
    {
            GSList *l;
    
            l = g_slist_alloc();
            l = g_slist_append(l, (int []){1, 2, 3});
    
            return 0;
    }
    

    $ gcc -Wall -Wextra -g $(pkg-config --cflags --libs glib-2.0) main.c

    【讨论】:

      猜你喜欢
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多