Window Sizing

Integer Pointers in SDL

Why does SDL require integer pointers in functions like SDL_GetWindowSize()?

Abstract art representing computer programming

SDL requires integer pointers in functions like SDL_GetWindowSize() to allow it to directly write the requested data back to your variables.

This is a common C-style approach for returning multiple values in functions that can’t use a direct return value due to limitations in C.

How It Works

When you call SDL_GetWindowSize(window, &width, &height), SDL writes the current window width and height into the memory locations pointed to by &width and &height.

This avoids the need for dynamic memory allocation or returning a struct. Here’s an example:

#include <SDL.h>
#include <iostream>

int main() {
  SDL_Init(SDL_INIT_VIDEO);

  SDL_Window* window =
    SDL_CreateWindow("Window Size Example",
                     SDL_WINDOWPOS_CENTERED,
                     SDL_WINDOWPOS_CENTERED,
                     400, 400,
                     SDL_WINDOW_RESIZABLE);

  int width, height;
  SDL_GetWindowSize(window, &width, &height);
  std::cout << "Window size: " << width << "x"
    << height << "\n";

  SDL_DestroyWindow(window);
  SDL_Quit();

  return 0;
}
Window size: 400x400

Advantages

  • Efficient: No temporary variables or heap allocations.
  • Simple: Pointers allow multiple outputs in a single function call.

Caveats

Always ensure the pointers are valid. Passing nullptr for either dimension skips updating that value, which can lead to bugs if misused.

Using pointers keeps SDL lightweight and efficient, consistent with its design philosophy.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 62 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved