当我进行练习时,我有一个问题是用C语言模拟CPU时间安排
我将CPU定义为类似
的结构struct CPU
{
int state; // state = 1 : CPU is FREE
// state = 0 : CPU is BUSY
}
用户输入他们想要用于时间安排的CPU数量(我称之为CPU_number)
问题是如何创建CPU.CPU1,CPU.CPU2,...等于CPU_Number
有谁知道怎么做?
答案 0 :(得分:1)
你需要一个数组
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
答案 1 :(得分:0)
这是一个名为&#34; CPU&#34;的结构类型的定义,而不是一个名为&#34; CPU&#34;的特定实例。在进行任何操作之前,您需要创建该结构的实例:
struct CPU cpu1, cpu2; // through cpuN;
cpu1.state = 0; //etc
答案 2 :(得分:0)
这应该让你输入一个数字和malloc所需的结构
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