gpt4 book ai didi

c - 通过引用传递 GList

转载 作者:太空宇宙 更新时间:2023-11-03 23:29:05 25 4
gpt4 key购买 nike

我正在尝试将实体寄存器维护为链表,并使用一组函数接受对列表的引用并就地修改它。我已经将这种策略与结构内部的 GList 一起使用,效果非常好,但为此我不需要容器结构。我正在尝试做的是:

// Creates a new entity and appends it to the global entity index.
// Returns ID of the newly created entity, not a pointer to it.
int anne_entity_create(char entity_name[], char entity_type[], GList *Entities) {

ANNE_ENTITY *newEntity = malloc(sizeof(ANNE_ENTITY));
ANNE_ENTITY_RECORD *newEntityRecord = malloc(sizeof(ANNE_ENTITY_RECORD));

newEntity->id = anne_entity_get_next_id(Entities);
sprintf(newEntity->name, "%s", entity_name);
sprintf(newEntityRecord->name, "%s", entity_name);

newEntityRecord->entity = newEntity;

Entities = g_list_append(Entities, newEntityRecord);

printf("Index length: %i\n", g_list_length(Entities));

return newEntity->id;
}

//Entity system setup
GList* Entities = NULL;
printf("Entity ID: %i\n", anne_entity_create("UNO", "PC", Entities));
printf("Entity ID: %i\n", anne_entity_create("DOS", "PC", Entities));
printf("Index length: %i\n", g_list_length(Entities));

anne_entity_create() 内部的 g_list_length() 返回 1,而在外部执行的相同函数返回 0。很明显,GList 在传递给 anne_entity_create(),但我不知道为什么 - 并且不需要通过 &reference 传递它,因为(据我所知)创建一个 GList 与 GList* Foo; 语法无论如何都会产生一个指针。

我确定我完全误解了我正在做的事情,但我已经研究了好几个小时了。

最佳答案

您将单个指针传递给您的函数,这意味着您可以修改指针指向的内容,在本例中为 NULL,并且您使用本地指针(作用域为您的函数 anne_entity_create) 指向 NULL,然后指向您“附加”您的列表的指针,这使得它只能在本地访问。

因此您需要使用双重间接寻址:将指向列表头指针的指针传递给您的函数,并对其进行操作,因此您正在更改列表的实际头部,而不是传递地址的副本名单的头。希望您能理解,欢迎随时提问。

GList *Entities = NULL;
anne_entity_create("UNO", "PC", &Entities) //Inside your function pass *Entities to append

// Creates a new entity and appends it to the global entity index.
// Returns ID of the newly created entity, not a pointer to it.
int anne_entity_create(char entity_name[], char entity_type[], GList **Entities) {

ANNE_ENTITY *newEntity = malloc(sizeof(ANNE_ENTITY));
ANNE_ENTITY_RECORD *newEntityRecord = malloc(sizeof(ANNE_ENTITY_RECORD));

newEntity->id = anne_entity_get_next_id(*Entities);
sprintf(newEntity->name, "%s", entity_name);
sprintf(newEntityRecord->name, "%s", entity_name);

newEntityRecord->entity = newEntity;

*Entities = g_list_append(*Entities, newEntityRecord);

printf("Index length: %i\n", g_list_length(*Entities));

return newEntity->id;
}

关于c - 通过引用传递 GList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19897724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com