c语言 - 无法释放从函数返回的 typedef 结构



我遇到了一个问题,这无疑是由于我的想法有缺陷,但我似乎无法理解它。我有一个这样的结构:

typedef struct
{
    ALLEGRO_BITMAP *bitmap;
    char name[255];
    signed int  step;       // How many frames to move per cycle. Negative values will cause the animation to reverse. Affects "current" frame only.
    ANNE_SPRITE_CYCLES cycles;
    ANNE_SPRITE_ANIMATIONS anim;
    ANNE_SPRITE_FRAME current;
} ANNE_SPRITE; 

如果我 malloc() 然后立即释放它,一切都很好:

ANNE_SPRITE *sprite = malloc(sizeof(ANNE_SPRITE));
free(sprite);
printf("Haven't crashed yet, boss!");

但是,如果我在函数中构建结构,如下所示:

ANNE_SPRITE anne_sprite_load(char sprite_name[]){
    ANNE_SPRITE *sprite = malloc(sizeof(ANNE_SPRITE));
    //Snipped: a bunch of code to populate the struct with data
    return *sprite;
}

那么我就不能在调用上下文中为爱或金钱释放结构:

ANNE_SPRITE test = anne_sprite_load("awesome_sprite");
free(test);

这会产生一个编译器错误 - 事实上,我正在passing 'ANNE_SPRITE' to parameter of incompatible type 'void *' - 但我不知道如何将这个变量精细化为 free() 准备使用的格式。

第二个示例返回ANNE_SPRITE(即结构,而不是指针)。您应该将签名更改为ANNE_SPRITE* anne_sprite_load(char sprite_name[])并调整return statement

ANNE_SPRITE* anne_sprite_load(char sprite_name[]){  // <== Change return type to be a pointer.
    ANNE_SPRITE *sprite = malloc(sizeof(ANNE_SPRITE));
    //Snipped: a bunch of code to populate the struct with data
    return sprite;  // <== Return the pointer.
}

ANNE_SPRITE* pTest = anne_sprite_load("awesome_sprite");  // <== Change to pointer type
free(pTest);  // <== Now free will work

相关内容

  • 没有找到相关文章

最新更新