I'm working on some SDL stuff and I've run into some trouble when trying to set the location of a loaded BMP.
Here's the code.
while(event.type != SDL_QUIT) //The game loop that does everything
{
SDL_Rect *location;
location = SDL_Rect(600,400,0,0);
SDL_PollEvent(&event); //This "polls" the event
//Drawing stuff goes here
SDL_BlitSurface(zombie, NULL, buffer, &location);
SDL_Flip(buffer); //Draw
}
It won't compile. What am I doing wrong?
SDL is written in C so SDL_Rect
is just a simple struct.
To dynamically allocate it you'd have to use new
otherwise the compiler will interpret your code as a call to a regular function called SDL_Rect
that returns a SDL_Rect*
.
In this case I see no reason to use dynamical allocation; just use the struct initialization syntax (and be careful of the declaration order of the struct's members):
SDL_Rect location = {0,0,600,400}; // or
SDL_Rect location{0,0,600,400}; // for C++11 & up (h/t @HolyBlackCat)
or explicitly initialize each of it's members (safer in case somebody decides to re-arange the order of the struct's members):
SDL_Rect location;
location.h = 600;
location.w = 400;
location.x = 0;
location.y = 0;
As an alternative to the above answer, if, for any reason, you did need to dynamically create location
, you would need to do it like this:
while(event.type != SDL_QUIT) //The game loop that does everything
{
SDL_Rect *location;
location = new SDL_Rect(600,400,0,0); //add new operator
SDL_PollEvent(&event); //This "polls" the event
//Drawing stuff goes here
SDL_BlitSurface(zombie, NULL, buffer, location);
SDL_Flip(buffer); //Draw
delete location; //IMPORTANT: deallocate memory
}
Note that, because an additional SDL_Rect
will be created on each iteration of the loop, and there will cease to be a pointer to it on the next iteration, it is necessary to delete it before the end of the loop (in other words, to delete before the end of each iteration). Otherwise, you create a memory leak.
As an additional alternative, if you needed changes to location
to persist from one iteration of your loop to the next, or if you didn't need to change within the loop at all, but you wanted to clean up your coda a little, you could do something like this:
SDL_Rect *location = new SDL_Rect(600,400,0,0);
while(event.type != SDL_QUIT) //The game loop that does everything
{
SDL_PollEvent(&event); //This "polls" the event
//Drawing stuff goes here
SDL_BlitSurface(zombie, NULL, buffer, location);
SDL_Flip(buffer); //Draw
}
delete location;
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