我在C++中找到了很多关于这个问题的答案,但我对C非常感兴趣.
我在C中有一个循环链表,我想在第一次访问它之前用虚拟标头节点初始化它.虚头节点是静态分配的全局变量.这是我目前的解决方案:
static once = 1;
if(once){
once = 0;
// Setup code
}
Run Code Online (Sandbox Code Playgroud)
这有效,但我必须将它放在使用此链表的每个函数中.(当然,我可以将这段代码放在自己的函数中,所以我只需要在其他所有函数中调用该函数,但这不是更好)有没有更好的方法?例如,如果我有以下结构:
struct node {
int value;
struct node *next;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法初始化其中一个结构作为文字,这样它的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(){...}
Run Code Online (Sandbox Code Playgroud)
如果它是文件范围变量,您可以完全按照您所说的做,并使其指向自身:
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
paul@horus:~/src/sandbox$ ./list
1 1
paul@horus:~/src/sandbox$
Run Code Online (Sandbox Code Playgroud)
当然,您还可以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;
}
Run Code Online (Sandbox Code Playgroud)