如何在c中的结构中实现变量?

时间:2015-02-14 13:19:07

标签: c variables structure

这不是完整的程序

struct p
{
int a;
int b;
int c;
};
void main()
{
int op,i,j,to,from,a,b,c;
struct p pr[3];
clrscr();
for(i=1;i<4;i++)
{
    pr[i].a=0;
    pr[i].b=0;
    pr[i].c=0;
    printf("P%d %d %d %d\n",i,pr[i].a,pr[i].b,pr[i].c);
}
do{

printf("\nEnter the option you want to execute:\n1. Internal Event\n2. Send Message \n3. Exit \n\n");
scanf("%d",&op);


switch(op)
{
    case 1:
    printf("\nEnter the process for which the internal event takes place: ");
    scanf("%d",&j);

j的值将在1到3之间变化 我想在这做的是: 如果j = 1, PR [1] .A = PR [1] .A + 1; 我没有为j实现switch case,而是想自动更新值 PR [j]的A / B / C

有人可以帮忙解决它。 PS:我正在尝试为Vector Clocks实现一个C程序

1 个答案:

答案 0 :(得分:0)

如果结构没有改变,它相当于一个整数数组。然后你可以使用一个联合并使用最漂亮的东西:

typedef union uBoth {
    struct
    {
        int a;
        int b;
        int c;
    } p;
    int q[3];
};

void main()
{
    int op,i,j,to,from,a,b,c;
    union uBoth pr[3];

    clrscr();
    for(i=0; i<3; i++)
    {
        for (j=0; j<3; j++)
            pr[i].q[j]= 0;
        printf("P%d %d %d %d\n",i+1, pr[i].p.a, pr[i].p.b, pr[i].p.c);
    }
    do {
        printf("\nEnter the option you want to execute:\n1. Internal Event\n2. Send Message \n3. Exit \n\n");
        scanf("%d",&op);
        switch(op)
        {
            case 1:
                printf("\nEnter the process for which the internal event takes place: ");
                scanf("%d",&j);
                pr[j-1].p.a= 1;
        }
    } while(1);
}