如何更新结构中的字段?

时间:2017-06-17 14:48:15

标签: c eclipse struct

我有一个struct,其中有几天。我用Eclipse编写了一些长代码,并将结构放在一个C文件中,与main()不同。现在,在main()中,我编写了一个转到struct并更新day字段的函数 - 由于某种原因,该字段未更新。我尝试调试这个但是如果我提出了断点(Eclipse问题),调试器会突然停止 - 即使代码有效但我得到的结果是错误的。所以我添加printf以查看字段是否实际更新,我发现它们不是。

以下是struct

    typedef struct roomorder_t* Roomorder;

    struct roomorder_t {
        int room_id;
        int days_till_order;
        int order_hour;
    };

    // function in the same c file that updates the day
    void updateRoomOrderDay(Roomorder roomorder){
        int curr_day=roomorder->days_till_order;
        curr_day-=1;
        return;
    }

int GetRoomOrderDaysTillOrder(Roomorder roomorder){
    if(roomorder==NULL){
        return FAIL;
    }
    return roomorder->days_till_order;
}

    // here how i used the function in the main file to update :



     static void EscapeUpdateDay(Escape escape){
                     // here i wrote a code to find the roomorder struct i am 
                      //looking 
                     //for to update and i found it (curr_order)
                       Roomorder curr_order=setGetFirst(roomorders);
                       printf("days_till_order_before=d\n",GetRoomOrderDaysTillOrder(curr_order));
                        updateRoomOrderDay(curr_order);
printf("days_till_order_after=%d\n",GetRoomOrderDaysTillOrder(curr_order));

        }
  

更新:好的,所以这一天确实更新了但反之亦然!我加了一个   printf和一个例子来解释发生了什么:我打印了一天   在更新之前和之后,它确实发生了变化,而不是   减去一天,例如:

//days_till_order_before=7 (before the update)
//days_till_order_after=8 (after the update)
  

//我也确实将updateRoomOrderDay函数更改为您所说的内容   我

roomorder->days_till_order-=1;

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您只是在代码中更新本地变量

void updateRoomOrderDay(Roomorder roomorder){
    int curr_day=roomorder->days_till_order;
    curr_day-=1;
    return;
}

将其更改为(我猜)

void updateRoomOrderDay(Roomorder roomorder){
    roomorder->days_till_order = roomorder->days_till_order - 1;
}

PS:typedef struct roomorder_t* Roomorder; - 这是一种不好的做法,因为你隐藏了一个指针

修改

现在手持代码

int GetRoomOrderDaysTillOrder(Roomorder roomorder){
    if(roomorder==NULL){
        return FAIL;
    }
    return roomorder->days_till_order;
}

您的语义不正确。您要么返回值,要么返回错误代码。失败的价值是什么?

答案 1 :(得分:0)

这可能会有所帮助:

在代码的这一部分:

void updateRoomOrderDay(Roomorder roomorder){
    int curr_day=roomorder->days_till_order;
    curr_day-=1;
    return;
}

您首先将roomorder->days_till_order的值存储在整数变量中,然后将该整数变量的值减1(这对roomorder->days_till_order的值没有影响),所以,您需要将此部分更改为:

void updateRoomOrderDay(Roomorder roomorder){
    int curr_day=roomorder->days_till_order;
    curr_day-=1;
    roomorder->days_till_order = curr_day;
    return;
}

或者,你可以这样做:

void updateRoomOrderDay(Roomorder roomorder){
    roomorder->days_till_order -= 1;
    return;
}