我正在尝试将实体寄存器维护为链接列表,并使用一组接受列表引用并就地修改它的函数。我在结构内部使用了这种带有 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));
g_list_length()
里面anne_entity_create()
返回 1,而在外部执行的相同函数返回 0。很明显,GList 在传递到 anne_entity_create()
时被复制。 ,但我不知道为什么 - 并且通过 &reference 传递它应该是没有必要的,因为(据我的理解)使用 GList* Foo;
创建一个 GList无论如何,语法都会产生一个指针。
我确信我完全误解了我正在做的事情,但我已经研究了几个小时了。
最佳答案
您正在向函数传递一个指针,这意味着您可以修改指针所指向的内容,在本例中为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/