-1

这有什么问题?我可以在 C 的结构中拥有指向 SDL_Surfaces 的指针数组吗?

typedef struct {
    int next_wheel;
    int pos_X;
    int pos_Y;
    int front_wheel_pos_X;
    int front_wheel_pos_Y;
    int velocity;
    int rear_wheel_pos_X;
    int rear_wheel_pos_Y;
    SDL_Surface* body;
    SDL_Surface* rear_wheel[9];
    SDL_Surface* front_wheel[9];
} mars_rover;

...

mars_rover* init_rover() {
    mars_rover* rover = (mars_rover*)malloc(sizeof(mars_rover) + sizeof(SDL_Surface) * 19);
    rover->body = load_image("Graphics//rover.png", ds_info);
    rover->front_wheel[0] = load_image("Graphics//wheel//wheel0.png", ds_info);
    ...

    return rover;
}

int main() {
    mars_rover* rover = init_rover();
...
}

编辑:添加了我的加载图像功能。

SDL_Surface *load_image( const char* filename , SDL_VideoInfo* ds_info) {

    SDL_Surface* image = 0;
    SDL_Surface* converted_surface = 0;
    image = IMG_Load(filename);

    if(image) {
        converted_surface = SDL_DisplayFormatAlpha(image);
        SDL_FreeSurface(image);
    }

    return converted_surface;
}
4

1 回答 1

1

可以,但需要分别为每个指针分配分配的内存。所以而不是:

mars_rover* rover = (mars_rover*)malloc(sizeof(mars_rover) + sizeof(SDL_Surface) * 19);

你应该有:

mars_rover* rover = malloc(sizeof(mars_rover));
rover->body = malloc(sizeof(SDL_Surface));
for (i = 0; i < 9; ++i) {
    rover->rear_wheel[i] = malloc(sizeof(SDL_Surface));
    rover->front_wheel[i] = malloc(sizeof(SDL_Surface));
}

有两个注意事项:

  1. 您需要检查每个分配的返回值
  2. 清理时需要释放每个分配
于 2012-09-08T21:36:14.413 回答