在C中为struct的属性设置默认值

在C中为struct的属性设置默认值,c,struct,set,default,C,Struct,Set,Default,我有一个结构(用C语言)声明如下: struct readyQueue { int start; int total_CPU_burst; int CPU_burst; int CPU_bursted; int IO_burst; int CPU; struct readyQueue *next; }; struct readyQueue *readyStart = NULL; struct readyQueue *readyRear =

我有一个结构(用C语言)声明如下:

struct readyQueue
{
    int start;
    int total_CPU_burst;
    int CPU_burst;
    int CPU_bursted;
    int IO_burst;
    int CPU;
    struct readyQueue *next;
};
struct readyQueue *readyStart = NULL;
struct readyQueue *readyRear = NULL;

readyStart = mallow(sizeof(struct readyQueue) * 1);
readyRear = mallow(sizeof(struct readyQueue) * 1);
我想默认设置readyStart->CPU=-1,readyRead->CPU=-1,CPUchoose->CPU=-1,这意味着如果我像这样声明新的readyQueue结构

struct readyQueue *CPUchoose = NULL;
CPUchoose = mallow(sizeof(struct readyQueue) * 1);
然后CPUchoose->CPU也==-1,我试着像这样删除准备好的队列

 struct readyQueue
    {
        int start;
        int total_CPU_burst;
        int CPU_burst;
        int CPU_bursted;
        int IO_burst;
        int CPU = -1;
        struct readyQueue *next;
    };

但是当我构建代码时,它显示了一个错误,有人能帮我创建一个函数来执行此操作吗

struct readyQueue* create_readyQueue()
{
    struct readyQueue* ret = malloc( sizeof( struct readyQueue ) );
    ret->CPU = -1;
    // ...
    return ret;
}

struct readyQueue* CPUchoose = create_readyQueue();
您还必须记住释放内存,因此最好传入指向初始化函数的指针

void init_readyQueue( struct readyQueue* q )
{
   q->CPU = -1;
   // ...
}


struct readyQueue* CPUchoose = malloc( sizeof( struct readyQueue ) );
init_readyQueue( CPUchoose );
// clearer that you are responsible for freeing the memory since you allocate it.
你可以做:

struct readyQueue_s
{
   int start;
   int total_CPU_burst;
   int CPU_burst;
   int CPU_bursted;
   int IO_burst;
   int CPU;
   struct readyQueue_s *next;
}; 

struct readyQueue_s readyQueueDefault = {0, 0, 0, 0, 0, -1, NULL};    

int main(void) 
{
  struct readyQueue_s foo;

  foo = readyQueueDefault;
}

了解更多信息。

C不提供开箱即用的“默认值”。初始化器必须是常量。把
foo
的定义和它的赋值分开,它就可以工作了。你编辑的内容还可以,问题在于
foo
@阿尔克:我想我在最后一行也犯了一个错误,因为他在结构本身中有
readyQueue*next
。@阿尔克:那里。。。我想它现在修好了。谢谢你的编辑。是的,这种方法1+以上。