C 相当于 Java 静态 block (启动时运行一次)

标签 c static

我在 C++ 中找到了很多这个问题的答案,但我对 C 非常感兴趣。

我在 C 中有一个循环链表,我想在第一次访问它之前用一个虚拟头节点初始化它。虚拟头节点是静态分配的全局变量。这是我目前的解决方案:

static once = 1;
if(once){
    once = 0;
    // Setup code
}

这行得通,但我必须将它放在使用此链表的每个函数中。 (当然,我可以把这段代码放在它自己的函数中,所以我只需要在每个其他函数中调用那个函数,但这也好不了多少)有没有更好的方法?例如,如果我有以下结构:

struct node {
    int value;
    struct node *next;
}

有什么方法可以将这些结构之一初始化为文字,使其 next 值指向自身?

“初始化为文字”,我的意思是:(请原谅我可能不正确的术语)

struct test {
    int i;
    double d;
};

struct test magic = {1, 2.3}; // This can just be done at the top of the c file, outside of any functions

int someFunction(){...}

最佳答案

如果它是一个文件范围变量,你可以完全按照你说的去做,让它指向它自己:

#include <stdio.h>

struct node {
    int value;
    struct node * next;
};

struct node mylist = { 1, &mylist };

int main(void)
{
    printf("%d %d\n", mylist.value, mylist.next->value);
    return 0;
}

输出:

paul@horus:~/src/sandbox$ ./list
1 1
paul@horus:~/src/sandbox$ 

当然,您也可以在执行任何其他操作之前在 main() 中添加“在启动时运行一次”代码,并达到相同的目的:

#include <stdio.h>
#include <stdlib.h>

struct node {
    int value;
    struct node * next;
};

struct node * mylist;

int main(void)
{
    mylist = malloc(sizeof *mylist);
    if ( !mylist ) {
        perror("couldn't allocate memory");
        return EXIT_FAILURE;
    }

    mylist->value = 1;
    mylist->next = mylist;

    /*  Rest of your program here  */

    return 0;
}

关于C 相当于 Java 静态 block (启动时运行一次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42149755/

相关文章:

c - 什么是 DDD(数据显示调试器)的良好 unix 替代品?

c++ - 在 Linux 上的多线程 C++ 应用程序中检测堆栈溢出/覆盖

具有自定义初始化的 C++ 静态分派(dispatch)

c - 链表数据结构错误

c - 如何在c中的数组指针上加载txt

c - 这是编译器仅通过使用位运算来划分的方式吗?

java - 什么时候调用静态循环?

vb.net - 声明全局、静态变量

c++ - 带有 open_MP 的静态变量 thread_local

c++ - 我们如何能够在类中声明一个与该类具有相同数据类型的静态成员?