c - 如何更新结构体中的字段?

标签 c eclipse struct

我有一个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/

相关文章:

C语言如何用整数倒序扫描文件?

c - 函数调用的参数太多,我该怎么办?

eclipse - 如何在 Eclipse 中将多行代码一起向左或向右移动?

java - Eclipse 中的导出窗口上没有可运行的 JAR 文件选项

使用openwrt编译C程序

c - 带有指针的嵌套结构

c - c中malloc的使用

c - 从 char * 数组中删除成员

java - 如何将多个 Jar 文件组合成一个可交付的 Jar?

c - C 是否允许将结构类型转换为自身?