麻烦的C语法

时间:2014-12-11 06:23:35

标签: c

我目前正在Linux C中为一个类实现Bankers算法。我已经习惯了c ++,并且在C中遇到了一些语法问题。我已经创建了一个Job类,然后是一个接受作业类并将1-10中的随机数分配给它们的函数。

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>

struct job
{
    int requestA;
    int requestB;
    int requestC;
    int requestD;
    int requestE;
    int needA;
    int needB;
    int needC;
    int needD;
    int needE;
}

void process_rec(job *job1)
{
    int a_initial = 1 + (rand() % 10);
    int b_initial = 1 + (rand() % 10);
    int c_initial = 1 + (rand() % 10);
    int d_initial = 1 + (rand() % 10);
    int e_initial = 1 + (rand() % 10);

    int a_final = a_initial + (rand() %10);
    int b_final = b_initial + (rand() %10);
    int c_final = c_initial + (rand() %10);
    int d_final = d_initial + (rand() %10); 
    int e_final = e_initial + (rand() %10);

    job1.requestA = a_initial;
    job1.requestB = b_initial;
    job1.requestC = c_initial;
    job1.requestD = d_initial;
    job1.requestE = e_initial;

    job1.needA = a_final;
    job1.needB = b_final;
    job1.needC = c_final;
    job1.needD = d_final;
    job1.needE = e_final;


}
int main()
{

return 0;
}

我收到错误,&#34;请求会员&#39; RequestA&#39;在不是结构或联合的东西中。有人可以帮我解决我的代码有什么问题吗?另外,我如何在主函数中创建一个结构体?

2 个答案:

答案 0 :(得分:2)

在你的情况下

job *job1;

job1是一个指针。使用->运算符。

接下来,job a primitive data type

您必须使用struct job

或者,为了更好,请更改

struct job
{
    int requestA;
    int requestB;
    int requestC;
    int requestD;
    int requestE;
    int needA;
    int needB;
    int needC;
    int needD;
    int needE;
}

typedef struct job
{
    int requestA;
    int requestB;
    int requestC;
    int requestD;
    int requestE;
    int needA;
    int needB;
    int needC;
    int needD;
    int needE;
} job;

您可以使用代码中使用的job。但是,在这两种情况下,在结构定义之后需要;

注意:在取消引用作为参数的指针之前检查NULL总是更好。此外,我假设您正在更新您的main()功能。 : - )

答案 1 :(得分:0)

检查以下代码。要访问结构成员,您需要使用->运算符。我们没有看到你调用你的函数,它需要按照代码中所示完成。 如果您只想使用job代替struct job,可以使用typedef struct job job;

struct job
{
    int requestA;
    int requestB;
    int requestC;
    int requestD;
    int requestE;
    int needA;
    int needB;
    int needC;
    int needD;
    int needE;
};

void process_rec(struct job *job1)
{
    int a_initial = 1 + (rand() % 10);
    int b_initial = 1 + (rand() % 10);
    int c_initial = 1 + (rand() % 10);
    int d_initial = 1 + (rand() % 10);
    int e_initial = 1 + (rand() % 10);

    int a_final = a_initial + (rand() %10);
    int b_final = b_initial + (rand() %10);
    int c_final = c_initial + (rand() %10);
    int d_final = d_initial + (rand() %10); 
    int e_final = e_initial + (rand() %10);

    job1->requestA = a_initial;
    job1->requestB = b_initial;
    job1->requestC = c_initial;
    job1->requestD = d_initial;
    job1->requestE = e_initial;

    job1->needA = a_final;
    job1->needB = b_final;
    job1->needC = c_final;
    job1->needD = d_final;
    job1->needE = e_final;


}
int main()
{
    struct job job;
    process_rec(&job);
    return 0;
}