title: How to set a pixel in a SDL_surface?
body: <p>I need to use the following function from <a href="http://content.gpwiki.org/index.php/SDL:Tutorials:Drawing_and_Filling_Circles" rel="noreferrer">this page</a>. The <a href="http://sdl.beuc.net/sdl.wiki/SDL_Surface" rel="noreferrer">SDL_Surface structure</a> is defined as</p>
  
  <pre><code>typedef struct SDL_Surface {
      Uint32 flags;                           /* Read-only */
      SDL_PixelFormat *format;                /* Read-only */
      int w, h;                               /* Read-only */
      Uint16 pitch;                           /* Read-only */
      void *pixels;                           /* Read-write */
      SDL_Rect clip_rect;                     /* Read-only */
      int refcount;                           /* Read-mostly */
  } SDL_Surface;
  </code></pre>
  
  <p>The function is:</p>
  
  <pre><code>void set_pixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
  {
        Uint8 *target_pixel = (Uint8 *)surface-&gt;pixels + y * surface-&gt;pitch + x * 4;
        *(Uint32 *)target_pixel = pixel;
  }
  </code></pre>
  
  <p>Here I have few doubts, may be due to the lack of a real picture.</p>
  
  <ol>
  <li>Why do we need to multiply <code>surface-&gt;pitch</code> by <code>y</code>, and <code>x</code> by <code>4</code>?</li>
  <li>What is the necessity of declaring <code>target_pixel</code> as an <code>8-bit integer pointer</code> first, then casting it into a <code>32-bit integer pointer</code> later?</li>
  <li>How does <code>target_pixel</code> retain the <code>pixel</code> value after the <code>set_pixel</code> function return?</li>
  </ol>