SDL加载bmp问题

时间:2013-02-15 18:45:50

标签: c++ sdl

我一直在关注懒惰的foo SDL教程,并且已经在第2课中遇到了障碍。我的代码正是他想要的,但是当我试图blit下面的图像时,我仍然会遇到相同的错误:

SDLtest.exe中0x68126030处的未处理异常:0xC0000005:访问冲突读取位置0x00000004。

以下是不断产生此类错误的代码:

#include "SDL.h"
#include <string>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;

SDL_Surface *message = NULL;
SDL_Surface *background = NULL;
SDL_Surface *screen = NULL;

SDL_Surface *load_image(std::string filename)
{
    SDL_Surface* loadedImage = NULL;
    SDL_Surface* optimizedImage = NULL;
    //load the image
    loadedImage = SDL_LoadBMP( filename.c_str() );

    if (loadedImage != NULL)
    {
        optimizedImage = SDL_DisplayFormat(loadedImage);
        SDL_FreeSurface(loadedImage);
    }
    return optimizedImage;
}

void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination)
{
    SDL_Rect offset;

    offset.x = x;
    offset.y = y;
    //blit the surface
    SDL_BlitSurface(source, NULL, destination, &offset);
}

int main(int argc, char* args[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
    {
        return 1;
    }

    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);

    if (screen = NULL)
    {
        return 1;
    }

    SDL_WM_SetCaption("Hello World",NULL);
    //loading images
    message = load_image("hello.bmp");
    background = load_image("background.bmp");
    //image blitting
    apply_surface(0,0,background,screen);
    apply_surface(320,0,background,screen);
    apply_surface(0,240,background,screen);
    apply_surface(320,240,background,screen);
    apply_surface(180,140,message,screen);

    if (SDL_Flip(screen) == -1)
    {
        return 1;
    }

    SDL_Delay(2000);

    SDL_FreeSurface(message);
    SDL_FreeSurface(background);

    SDL_Quit();
    return 0;
}

2 个答案:

答案 0 :(得分:2)

错误Access violation reading location 0x00000004表示您正在取消引用一个值为4的指针,而不是真正的指针。

跟踪此问题的最简单方法是在调试器下运行,并查看导致问题的行。然后你可以回溯来找出指针值被搞砸的地方。然后你可能会发现Bert指出的错误。

答案 1 :(得分:0)

替换

if(screen = NULL)

if(screen == NULL)