Question

When I do my exercise I have a problem to simulate CPU time scheduling in C language that

I define CPU as a struct like that

struct CPU 
{
    int state;      // state = 1 : CPU is FREE
            // state = 0 : CPU is BUSY 
}

Users type the number CPU they want to use for time scheduling ( I call it's CPU_number)

The problem is how can I create CPU.CPU1, CPU.CPU2,... equal to CPU_Number

Does anyone know how to do this?

Was it helpful?

Solution 2

This should let you enter a number and malloc the needed structures

int iEach;
int CPU_number;
struct CPU {
    int state;
} *pcpu;

printf ( "enter number of CPU's: ");
scanf( "%d", &CPU_number);
pcpu = malloc ( sizeof (struct CPU) * CPU_number);
for ( iEach = 0; iEach < CPU_number; iEach++) {
    // here are equivalent ways to access the structures
    pcpu[iEach].state = 1;
    (pcpu + iEach)->state = 1;
}
free ( pcpu); // remember to free memory when you are done

OTHER TIPS

You need an array

struct CPU {
    int state; // 0: BUSY, 1: FREE
};

struct CPU cpu[10];

cpu[0].state = 1;                          // set cpu[0] as free
for (k = 1; k < 10; k++) cpu[k].state = 0; // set others as busy

That's the definition of a structure type called "CPU", not a specific instance called "CPU" You'll need to create instances of that struct before you can do any manipulation:

struct CPU cpu1, cpu2; // through cpuN;
cpu1.state = 0; //etc
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top