我有一个struct
,里面有天。我使用 Eclipse 编写了一些长代码,并将该结构放在与 main()
不同的文件中的 C 文件中。现在,在 main()
中,我编写了一个函数,该函数转到 struct
并更新 day
字段 - 由于某种原因,该字段不更新。我尝试对此进行调试,但如果我设置断点(Eclipse 问题),调试器会突然停止 - 即使代码有效,但我得到的结果是错误的。因此,我添加了 printf
来查看字段是否实际更新,但我发现它们没有更新。
这是结构
:
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));
}
UPDATE: ok so the day did update but the opposite happend ! i added a printf and an example to explain what happened : i printed the day before the update and after , it did change but instead of substracting one day it added a day for example :
//days_till_order_before=7 (before the update)
//days_till_order_after=8 (after the update)
// also i did change the updateRoomOrderDay function to what you told me.
roomorder->days_till_order-=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;
}
您的语义不正确。您要么返回一个值,要么返回一个错误代码。 FAIL 的值是多少?
关于c - 如何更新结构体中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44605955/