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?
SDL_RenderDrawLine() draws the line to include both end points. If you want to draw multiple, connecting lines use SDL_RenderDrawLines() instead.
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.
As mentioned by Zach Stark, SDL_FillRect
does not take an SDL_Rect
as an argument. Rather, it takes a pointer to an SDL_Rect
. By prefixing the variable with an ampersand (&
), you pass only a reference (a pointer) to the original variable. However, I could not get Zach's code sample to work in my C program. The following uses a different syntax for creating an SDL_Rect
but it worked for me.
// create a black square
SDL_Rect rect = {0, 0, 100, 100}; // x, y, width, height
SDL_FillRect(screenSurface, &rect, SDL_MapRGB(screenSurface->format, 0x00, 0x00, 0x00));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With