Hello. I am quite new to C programming and SDL. I am trying to convert an image to grayscale. However, when building the programm in terminal, I get an error, segmentation fault (core dumped)? Could anyone tell me where I am going wrong?
All help and suggestions are greatly appreciated.
Code is here:
int main(int argc, char* argv[])
{
//Declaring pointers
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Event event;
SDL_Texture *texture;
int i, quit;
Uint32 *pixels;
//Check command line usage
if ( ! argv[1] ) {
fprintf(stderr, “Give an image file: %s\n”, argv[0]);
}//Initializing window and renderer
SDL_Init(SDL_INIT_VIDEO);//Creating a window
if (SDL_CreateWindowAndRenderer(640, 480, SDL_WINDOW_RESIZABLE, &window, &renderer))
{
printf(“Couldn’t open the window: %s\n”, SDL_GetError());
}//Load an image
SDL_Surface * image = IMG_Load(argv[1]);
if (!image)
{
printf(“Couldn’t load the image: %s\n”, SDL_GetError());
exit(EXIT_FAILURE);
}//Create texture from image
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, image->w, image->h);
if (!texture)
{
printf(“Couldn’t create texture from image: %s\n”, SDL_GetError());
}
//Convert surface to ARGB8888 format
image = SDL_ConvertSurfaceFormat(image, SDL_PIXELFORMAT_ARGB8888, 0);
//Surface pixels from void to *Uint32
pixels = (Uint32 *)image->pixels;
quit = 0;
while (!quit) {
SDL_UpdateTexture(texture, NULL, image->pixels, image->w *sizeof(Uint32));
SDL_WaitEvent(&event); {
switch (event.type) {
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {//Going through y axis for (int y = 0; y < image->h; y++) { //Going through x axis for (int x = 0; x < image->w; x++) { //Converting to grayscale Uint32 pixel = pixels[y * image->w + x]; Uint8 r = pixel >> 16 & 0xFF; Uint8 g = pixel >> 8 & 0xFF; Uint8 b = pixel & 0xFF; Uint8 v = 0.212671f * r + 0.715160f * g + 0.072169f * b; pixel = (0xFF << 24) | (v << 16) | (v << 8) | v; pixels[y * image->w +x] = pixel; } case SDLK_LEFT: if ( i > 1 ) { i -= 2; quit = 1; } break; case SDLK_RIGHT: if ( argv[i+1] ) { quit = 1; } break; case SDLK_ESCAPE: case SDLK_q: argv[i+1] = NULL; /* Drop through to done */ case SDLK_SPACE: case SDLK_TAB: quit = 1; break; default: break; } break; case SDL_MOUSEBUTTONDOWN: quit = 1; break; case SDL_QUIT: argv[i+1] = NULL; quit = 1; break; break; } } //Show the image SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } SDL_DestroyTexture(texture); SDL_FreeSurface(image);
}
//Quit SDL
SDL_Quit();
return (0);
}