Set default value for struct attribute in C

I have a structure (in C languague) as shown 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, which means that I am declaring a new readyQueue structure like this

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

Then CPUchoose-> CPU is also == -1, I tried to split readyQueue as follows

 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 will show an error if anyone can help me.

+4
source share
2 answers

Create a function for this:

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

struct readyQueue* CPUchoose = create_readyQueue();

You should also forget to free up memory, so it’s better to go to the pointer to the initialization 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.
+5
source

You can do:

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

.

+4

Source: https://habr.com/ru/post/1540406/


All Articles