2

リストへの参照を受け入れてその場で変更する一連の関数を使用して、エンティティの登録をリンクされたリストとして維持しようとしています。私はこの戦術を構造体内の 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 が に渡されたときにコピーされていることは明らかですが、その理由がわかりません。 &referenceanne_entity_create()で渡す必要はありません。私の理解では)構文でGListを作成すると、とにかくポインターになります。GList* Foo;

私は自分がしていることを完全に誤解していると確信していますが、私はこれを何時間も突っついています.

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 に答える