2

我正在尝试将实体寄存器维护为链接列表,其中包含一组接受对列表的引用并对其进行修改的函数。我已经在结构内部使用了 GLists 的这种策略,效果非常好,但为此我不需要容器结构。我想要做的是:

// 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));

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

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

4

1 回答 1

2

您正在将单个指针传递给您的函数,这意味着,您可以修改指针所指向的内容,在这种情况下,NULL您可以使用指向 的本地指针(范围为您的函数anne_entity_createNULL,然后指向您的该指针“附加”您的列表,使其只能在本地访问。

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

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;
}
于 2013-11-11T03:27:16.867 回答