c中的全局结构
我很难弄清楚如何初始化要用作链表的全局结构。我已经尝试过几种方法,但基本上我做到了:c中的全局结构,c,struct,global-variables,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 *
#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”的类型不完整
有什么方法可以正确地做到这一点吗
此外,我将在多个线程中访问这个全局结构的链表。那么,我认为我将能够访问head和tail之间的任何请求结构,只要它们被prev或next引用,这是对的吗
谢谢仅供参考:您在创建它们时已经对它们进行了初始化(到
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};
}
首先,您有一个输入错误,它是结构定义中的request\u 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 };
如果不是打字错误,则结构名称不同(
reuqest_struct
您在结构定义中的reuqest
中有一个u
字符)@pmg你主要是说我应该只做head.next=tail
?因为我也尝试过了,但我刚刚得到了错误:未定义类型'struct request_struct'@Mahesh的使用无效…….我太愚蠢了…..对不起大家。请看@Mahesh的评论。你在结构名称中有一个输入错误。@user2799846别担心。建议:当你看到我的时候类似错误的消息:未定义类型的使用无效,您必须检查的事项1.类型定义是否可用于当前翻译单元中的编译器。2.拼写错误。