Why doesn't the sprite move?

I’ve done exactly what I’m supposed to do, said exactly what the documentation had provided. What could be the problem the sprite just doesn’t move when the keys are pressed.

My code:

#include <SDL2/SDL.h>
#include <stdio.h>

#define SHAPE_SIZE 16

typedef struct
{
int x ;
int y ;
} Sprite ;

void getKeys( Sprite *sprite ) ;

int main( int argc , char *argv[] )
{
SDL_Window *window = NULL ;
SDL_Renderer *renderer = NULL ;
SDL_Surface *loading_surf ;
SDL_Texture *loading_Tex ;
SDL_Texture *background_Tx ;
Sprite sprite = { 0 , 0 } ;
int posX = 100 , posY = 100 , width = 320 , height = 240 ;

SDL_Rect SrcR ;
SDL_Rect DestR ;

SrcR.x = 0 ;
SrcR.y = 0 ;
SrcR.w = SHAPE_SIZE ;
SrcR.h = SHAPE_SIZE ;

DestR.x = sprite.x ;
DestR.y = sprite.y ;
DestR.w = SHAPE_SIZE ;
DestR.h = SHAPE_SIZE ;

if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) != 0 )
{
SDL_Log( “Could not initialize SDL2: returned %s”, SDL_GetError() ) ;
return 1 ;
}

window = SDL_CreateWindow( “SDL_RenderCopy Example” ,
posX , posY , width , height, 0 ) ;
renderer = SDL_CreateRenderer( window , -1 , SDL_RENDERER_ACCELERATED ) ;

loading_surf = SDL_LoadBMP( “background.bmp” ) ;
background_Tx = SDL_CreateTextureFromSurface( renderer , loading_surf ) ;
SDL_FreeSurface( loading_surf ) ;

loading_surf = SDL_LoadBMP( “ship.bmp” ) ;
loading_Tex = SDL_CreateTextureFromSurface( renderer , loading_surf ) ;
SDL_FreeSurface( loading_surf ) ;

getKeys( &sprite ) ;
SDL_SetRenderDrawColor( renderer , 0 , 255 , 255 , 255 ) ;
while( 1 )
{
SDL_Event e ;
if( SDL_PollEvent( &e ) )
{
if( e.type == SDL_QUIT ) { break ; }
}

SDL_RenderClear( renderer ) ;
SDL_RenderCopy( renderer , loading_Tex , &SrcR , &DestR ) ;
SDL_RenderPresent( renderer ) ;      
SDL_Delay( 5 ) ;

}

SDL_DestroyTexture( background_Tx ) ;
SDL_DestroyTexture( loading_Tex ) ;
SDL_DestroyWindow( window ) ;
SDL_DestroyRenderer( renderer ) ;

SDL_Quit() ;

return 0 ;
}

void getKeys( Sprite *sprite )
{
const Uint8 *state = SDL_GetKeyboardState( NULL ) ;
if( state[SDL_SCANCODE_LEFT] ) { ++sprite->x ; }
if( state[SDL_SCANCODE_UP] ) { ++sprite->y ; }
if( state[SDL_SCANCODE_DOWN] ) { --sprite->y ; }
if( state[SDL_SCANCODE_RIGHT] ) { --sprite->x ; }
}

You have got to check the keys within the loop. If you check them once outside of the loop, then begin rendering, the sprite’s position will not change over time.

No matter, even if I put it into the loop (event loop) it still does the same thing, I think it has something to do with the drawing code or maybe even the image. By the looks of it they’re fine to me.

You not updating your rectangle position in the loop.

DestR.x = sprite.x ;
DestR.y = sprite.y ;

Also you should call

SDL_DestroyRenderer(renderer);

before

SDL_DestroyWindow(window);

PS. here in the forum you should indent code with 4 spaces to get nicer formatting