Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value for attribute of struct in C

I have a struct (in C languague) declare like below:

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);

And I want to set readyStart->CPU = -1 , readyRead->CPU = -1, CPUchoose->CPU = -1 by default that mean if I declare new readyQueue struct like that

struct readyQueue *CPUchoose = NULL;
CPUchoose = mallow(sizeof(struct readyQueue) * 1);

Then CPUchoose->CPU also == -1, I tried to delare readyQueue like this

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

But when I built the code it show out an error, can anyone help me please

like image 639
Nguyen Le Minh Avatar asked Dec 25 '22 09:12

Nguyen Le Minh


1 Answers

Create a function to do it:

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

struct readyQueue* CPUchoose = create_readyQueue();

You have to remember to free the memory as well, so it may be better to pass in a pointer to an initialize function.

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.
like image 65
clcto Avatar answered Jan 03 '23 10:01

clcto