这有什么问题?我可以在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;
}
答案 0 :(得分: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));
}
但有两点注意事项: