簡體   English   中英

C-檢查結構數組的所有值是否返回相同的值

[英]C - Check If All Values of Struct Array Return Same Values

我想檢查結構數組的所有值是否都具有相同的值,以便在結構數組中隱藏“已刪除”條目。

我的結構看起來像這樣:

struct spawnedObject {
    Hash objHash;
    Object obj;
    char* displayname;

    int invisibility;
    Vector3 position;

    int deleted; // 1=deleted and hidden, 0=should be listed and available
};

而且我想檢查結構中的所有條目的deleted是否為true。 當它們全部成立時,讓else顯示空白文本。

我試過循環所有deleted值,並在將值設置為1時增加一個整數,如下所示:

void objectManagerMenu() {
    objectVar = 0;
    int inc = 0; //store deleted entries count

    // loop through all entries. if entry deleted, increase.
    for (int i = 0; i < objectCount; i++) {
        if(spawnedObjects[i].deleted) inc++;
    }

    // check if there either are no entries, or if theyre hidden. if all stored entries are hidden, fallback to else. this is where it goes wrong.
    // problem: does not seem to fallback to else.
    if(objectCount != 0 || objectCount != inc) {
        for (int i = 0; i < objectCount; i++) {
            if(!spawnedObjects[i].deleted) { // remove hidden items from list
                char buffer[150];
                sprintf(buffer, "[ %i ] %s", i, spawnedObjects[i].displayname);

                menu.option(buffer).call(objectItemVar, i).submenu(objectItemMenu);
            }
        }
    } else {
        menu.option("Empty");
    }
}

由於沒有顯示任何內容,因此似乎無法正常工作。

有人建議我如何更聰明地做到這一點嗎?

問題是您的|| 在if語句中,例如int注釋。

objectCount != 0

最有可能返回true

objectCount != inc

返回false,因為菜單為空(在您嘗試測試的當前方案中)
這樣, if語句將始終為true(如果您的對象計數大於0),因此永遠不會執行else 更改|| &&

為什么
|| 如果至少其中一個語句為true,則返回true。
&& 僅當兩個都為真時才返回true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM