0

我一直在关注惰性 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;
}
4

2 回答 2

2

错误Access violation reading location 0x00000004是说您正在取消引用值为 4 的指针,而不是真实的东西。

追踪此问题的最简单方法是在调试器下运行,并查看导致问题的行。然后您可以回溯以找出指针的值在哪里弄乱了。然后你可能会发现像 Bert 指出的错误。

于 2013-02-15T18:49:19.767 回答
0

换行

if(screen = NULL)

if(screen == NULL)
于 2013-10-14T10:12:04.270 回答