簡體   English   中英

C 中的結構數組,char**

[英]Array of struct in C, char**

我期待着制作一個結構數組,就像 [obj, obj, obj] 一樣。 我得到了這個結構:

struct obj {
    char name[MAX_NAME];
    char desc[MAX_TEXT];
    bool asible;
};

我怎樣才能做到?

我試過了

struct obj **objInRoom = malloc(sizeof(struct obj));

但是當我在其中迭代時,它什么也沒有:DI 選擇了這個解決方案,因為我需要將那個結構數組放入這個結構中:

struct room {
    struct obj **objts;     //HERE
    int qntty_objts;
    struct interact **interacts;
    int qntty_interacts;
};

如果出於某種原因你需要一個雙指針,那么你可以做這樣的事情struct obj *objInRoom = malloc(sizeof(struct obj)); 然后將objInRoom的地址分配給您的結構room->objts=&objInRoom

struct obj **objInRoom = malloc(sizeof(struct obj));

如果我簡化一下,在你的嘗試中,你正在為一個結構分配一個區域,並試圖將它的地址分配給一個“struct obj address”地址持有者,即struct obj** 但是你應該使用struct obj *來保存新分配區域的地址。

在這種情況下,您的結構房間應該是這樣的:

struct room {
    struct obj *objts;     //struct obj** to struct obj*
    int qntty_objts;
    struct interact **interacts;
    int qntty_interacts;
};

您應該像這樣分配新分配的區域:

struct obj *objInRoom = (struct obj*)malloc(sizeof(struct obj));

但是在這種情況下,您只為一個struct obj元素分配了區域。 要增加此區域,您可以備份以前的數據並分配新區域以獲得更大的空間。 例如,將分配的區域增加兩倍:

//cap is integer defined before to hold capacity information of array
struct obj *backup = (struct obj*)malloc(2*cap*sizeof(struct obj));
for(int i = 0; i < cap; ++i)
    backup[i] = objInRoom[i];
free(objInRoom); //to prevent memory leak, because we allocated new area for our incremented sized array.
objInRoom = backup;
cap *= 2;

或者,如果分配發生在 malloc 或 calloc 之前,您可以簡單地使用 realloc 來增加數組容量,realloc 會創建一個具有所需大小的數組並保存以前的數據:

objInRoom = (struct obj*)realloc(objInRoom, 2*cap*sizeof(struct obj))

注意:始終將 malloc 操作轉換為所需的指針類型,因為它默認返回“void *”。

注意 2:始終檢查 malloc、realloc 和 calloc 的輸出; 如果出錯,他們會返回 NULL。

暫無
暫無

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

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