How to draw a square with SDL 2.0?

Andrew picture Andrew · Nov 1, 2013 · Viewed 11.2k times · Source

I would like to do something simple like draw a square on the screen using C and SDL. The example that I copied is not working.

//Get window surface
SDL_Surface *screenSurface = SDL_GetWindowSurface(window);

//Fill the surface white
SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));

//create a square
SDL_FillRect(screenSurface, SDL_Rect(0,0,100,100), SDL_MapRGB(screenSurface->format, 0x00, 0x00, 0x00));

It correctly fills the screen white, but fails on the call to SDL_Rect:

error: expected expression before ‘SDL_Rect’

How do I correctly draw a square using SDL 2.0?

Answer

Zach Stark picture Zach Stark · Nov 1, 2013

SDL_FillRect does not take an SDL_Rect as an argument; it takes a pointer to SDL_Rect.

//Create a square
SDL_Rect rect(0,0,100,100);
SDL_FillRect(screenSurface, &rect, SDL_MapRGB(...))

That is why when you fill with white you can pass NULL to the function. NULL is not of type SDL_Rect, but it is a pointer, so the compiler is fine with it.