c中的全局结构

时间:2014-03-20 19:16:08

标签: c struct global-variables

我很难弄清楚如何初始化全局结构以用作链表。我已经尝试了几件事,但我基本上已经这样了:

#includes....

struct reuqest_struct
{
struct timeval request_time;    
int type;           
int accountNums[10];        
int transAmounts[10];       
struct request_struct *next;    
struct request_struct *prev;    

};

// global structs I want
struct request_struct head;
struct request_struct tail;


int main(int argc, char * argv[]){

   head = {NULL, 5, NULL, NULL, tail, NULL};
   tail = {NULL, 5, NULL, NULL, NULL, head};

}

void * processRequest(){

   // Want to access the structs in here as well

 }

我尝试以这种方式初始化它们,但只是得到

“错误:'{'标记

之前的预期表达式

错误:'head'的类型不完整

错误:'{'标记

之前的预期表达式

错误:'tail'的类型不完整“

有没有办法正确地做到这一点?

此外,我将在许多线程中访问此链接的全局结构列表。所以,我认为只要它们被prev或next引用,我就可以访问head和tail之间的任何request_struct吗?

由于

2 个答案:

答案 0 :(得分:0)

仅供参考:您在创建它们时已经初始化它们(到0) 现在你要为它们分配一个值。

对于C89

int main(int argc, char **argv) {

    head.request_time.tv_sec = 42;
    head.request_time.tv_usec = 0;
    head.type = 5;
    head.accountNums[0] = 0;
    head.accountNums[1] = 1;
    // ...
    head.accountNums[9] = 9;
    head.transAmounts[0] = 0;
    // ...
    head.transAmounts[9] = 9;
    head.next = tail;
    head.prev = NULL;

    // same thing for tail
}

对于C99,有一个捷径:

int main(int argc, char **argv) {

    head = (struct request_struct){{42, 0}, 5,
           {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
           {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, tail, NULL};

}

答案 1 :(得分:0)

首先你有一个拼写错误,结构定义是 reuqest_struct ,修好之后你可以这样做

struct request_struct
{
struct timeval request_time;
int type;
int accountNums[10];
int transAmounts[10];
struct request_struct *next;
struct request_struct *prev;

};

// global structs I want
struct request_struct head = {.request_time = {0}, .type =5, .accountNums ={0},
         .transAmounts={0}, .next = NULL,.prev=NULL };