【问题标题】:Global structure pointer initialization全局结构指针初始化
【发布时间】:2012-04-23 18:43:47
【问题描述】:

结构定义

struct list
{
  struct list **next, **prev;
}

core.c

//Global struct
struct list *threads = {&threads, &threads};  //Warnings here:

// warning: initialization from incompatible pointer type
// warning: excess elements in scalar initializer
// warning: (near initialization for 'threads')

PS:我在这个文件中没有main 函数。这必须是全球性的。

【问题讨论】:

    标签: c struct initialization global


    【解决方案1】:

    您需要使用指向struct list 的指针初始化pointer-to-struct-list 变量threads{&threads, &threads} 不是指向struct list 的指针,但它可以是struct list

    为了定义一个实际的结构实例并获得一个指向它的指针,你可以使用一个复合文字并获取它的地址:

    struct list *threads = &((struct list){&threads, &threads});
    

    (注意:复合文字 ((<em>type</em>){<em>initializer</em>}) 是 C99 特性;一些没有赶上 13 年前标准的编译器可能会拒绝它。)

    【讨论】:

    • 谢谢凯文,还有一个问题,在结构初始化旁边,我有类似 void* vp_threads = threads; // 如果我写 &threads,这很好,但没有 '&' 它给我错误'initializer element is not constant' 为什么会这样?有什么想法吗?
    • 我不知道,抱歉。当然,这是两个不同的指针。如果您需要这方面的帮助,您应该提出一个单独的问题,并详细说明您需要完成的工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    相关资源
    最近更新 更多