gpt4 book ai didi

c - 在C中为结构的属性设置默认值

转载 作者:太空狗 更新时间:2023-10-29 15:19:45 26 4
gpt4 key购买 nike

我有一个结构(用 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,我试过这样delare readyQueue

 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.

关于c - 在C中为结构的属性设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23637116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com