0
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>
typedef struct{
SDL_Texture *texture; // The image/sprite itself
int width; // Sprite width
int height; // Sprite height
} Sprite;
Sprite *createSprite(SDL_Renderer *r, char *path);
int main(int argc, char *argv[]){
// Initialise SDL and SDL_image
SDL_Init(SDL_INIT_VIDEO);
IMG_Init(IMG_INIT_PNG);
// Create window
SDL_Window *window = SDL_CreateWindow(
"VN", // Title
SDL_WINDOWPOS_CENTERED, // Initial x position
SDL_WINDOWPOS_CENTERED, // Initial y position
1280, // Width
720, // Height
0 // Flags
);
if(window == NULL){
printf("Failed to create window. %s\n", SDL_GetError());
return 1;
}
// Create renderer
SDL_Renderer *renderer = SDL_CreateRenderer(
window, // Window
-1, // Monitor index (-1 for first available)
SDL_RENDERER_ACCELERATED // Flags
);
if(renderer == NULL){
printf("Failed to create renderer. %s\n", SDL_GetError());
return 1;
}
// Set up event handling
SDL_Event event;
while(1){
// Handle events/input
while(SDL_PollEvent(&event) != 0){
// Check if user wants to quit (press window close button)
if(event.type == SDL_QUIT){
return 1;
}
}
// Set screen colour to white
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
// Render white to screen (clear screen)
SDL_RenderClear(renderer);
// Update screen
SDL_RenderPresent(renderer);
}
// Exit SDL and SDL_image
SDL_Quit();
IMG_Quit();
return 0;
}
Sprite *createSprite(SDL_Renderer *r, char *path){
printf("Entered createSprite()\n");
// Create a Sprite structure, containing an image (texture) and its dimensions
Sprite *newSprite = NULL;
SDL_Texture *spriteTexture = NULL;
// Temporary surface (for loading texture)
SDL_Surface *tempSurface = NULL;
// Load image from path
tempSurface = IMG_Load(path);
if(tempSurface == NULL){
printf("Failed to load image '%s'. %s\n", path, IMG_GetError());
} else{
spriteTexture = SDL_CreateTextureFromSurface(r, tempSurface);
if(spriteTexture == NULL){
printf("Failed to create texture from '%s'. %s\n", path, SDL_GetError());
} else{
// Store texture, image width & height in Sprite structure
newSprite->texture = spriteTexture;
newSprite->width = tempSurface->w;
newSprite->height = tempSurface->h;
}
}
// Free memory of temp surface
SDL_FreeSurface(tempSurface);
printf("Leaving createSprite()\n");
return newSprite;
}
我試圖加載一個圖像使用SDL_image插件,並將其寬度和高度存儲在一個結構(以及從表面創建的紋理)。SDL2 - 試圖將表面信息複製到結構時崩潰。沒有錯誤信息
當試圖運行第93行上的newSprite->texture = spriteTexture;
部分時,它崩潰。這是我所能提供的儘可能多的信息。有任何想法嗎?
我試圖使用SDL_image插件加載圖像,並將其寬度和高度存儲在結構中(以及從表面創建的紋理)。
那麼,這是否 'newSprite' 獲得從NULL設置爲任何擱置?也就是說,這個程序在哪裏爲Sprite結構分配內存? NULL引用肯定會崩潰。 – jhc
@jhc我是一個完整的twit,謝謝。 – Sato
你甚至可以從main()調用'createSprite()'在哪裏? – genpfault