2014-10-01 69 views
0

所以我正在用SDL學習C++(在Visual Studio 2013上)。我正在關注Lazy Foo的教程(特別是:http://lazyfoo.net/tutorials/SDL/02_getting_an_image_on_the_screen/index.php)。爲什麼我的圖像不能渲染?

我的圖像不會呈現。與教程(工作)相反,我沒有全局表面變量。相反,我宣佈他們在主要並通過指針。

代碼:

#include <SDL.h> 
#include <SDL_image.h> 
#include <stdio.h> 
#include <string> 

const int SCREEN_WIDTH = 600; 
const int SCREEN_HEIGHT = 480; 

//SDL init. 
bool initialiseSDL(SDL_Window* gWindow, SDL_Surface* gWindowSurface) 
{ 
    bool success = true; 

    /*SDL_Init() initisalises SDL library. Returning 0 or less signifies an error. 
     SDL_INIT_VIDEO flag refers to graphics sub system.*/ 
    if (SDL_Init(SDL_INIT_VIDEO) < 0) 
    { 
     printf("SDL could not initialise. SDL Error: %s\n", SDL_GetError()); 
     success = false; 
    } 
    else 
    { 
     //Create the window 
     gWindow = SDL_CreateWindow("Asteroids", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); 
     if (gWindow == NULL) 
     { 
      printf("Could not create window. SDL Error: %s\n", SDL_GetError()); 
      success = false; 
     } 
     else 
     { 
      //Get the window surface. 
      gWindowSurface = SDL_GetWindowSurface(gWindow); 
     } 
    } 
    return success; 
} 

bool loadMedia(SDL_Surface* surface, std::string path) 
{ 
    //Success flag 
    bool success = true; 

    surface = SDL_LoadBMP(path.c_str()); 

    if (surface == NULL) 
    { 
     printf("SDL surface failed to load. SDL Error: %s\n", SDL_GetError()); 
     success = false; 
    } 

    return success; 
} 

void close() 
{ 

} 

int main(int argc, char* argv[]) 
{ 
    SDL_Window* gWindow = NULL; 
    SDL_Surface* gWindowSurface = NULL; 
    SDL_Surface* gImageSurface = NULL; 

    if (!initialiseSDL(gWindow, gWindowSurface)) 
    { 
     printf("Failed to initialise.\n"); 
    } 
    else 
    { 

     if (!loadMedia(gImageSurface, "hw.bmp")) 
     { 
      printf("Failed to load inital media."); 
     } 
     else 
     { 
      //Apply the image 
      SDL_BlitSurface(gImageSurface, NULL, gWindowSurface, NULL); 

      //Update the surface 
      SDL_UpdateWindowSurface(gWindow); 

      //Wait two seconds 
      SDL_Delay(2000); 
     } 
    } 

    return 0; 
} 

回答

2

你的程序表現出undefined behavior,因爲main函數內部的指針初始化。

當您將它們傳遞給initialiseSDL函數時,您可以通過值傳遞它們,這意味着它們被複制,函數僅對副本運行,而不是原始指針,它們在調用後仍將未初始化。

你需要做的是通過引用傳遞指針來代替:

bool initialiseSDL(SDL_Window*& gWindow, SDL_Surface*& gWindowSurface) 

當然,你需要做同樣與loadMedia功能。

+0

@Pileborg你是個紳士和學者,非常感謝!我一定會讀更多的指針。 – Cian 2014-10-01 10:38:08