title: Drawing a rectangle on SDL_Surface pixels
body: <p>I am trying to figure out how to draw a coloured rectangle on an <code>unsigned char</code> pixel array casted from the <code>pixels</code> member of a locked <code>SDL_Surface</code>.</p>
  
  <p>The following function is supposed to do the former: </p>
  
  <pre><code>void draw_rectangle(SDL_Surface* surface, int x, int y, int width, int height)
  {
      SDL_LockSurface(surface);
      //Make each pixel black
      std::vector&lt;uint8_t&gt; pixels(surface-&gt;h * surface-&gt;pitch, 0);
  
      for (int dy = y; dy &lt; height; dy++) {
          for (int dx = x; dx &lt; width; dx++) {
              pixels[dx + dy] = 0;
              pixels[dx + dy + 1] = 255;
              pixels[dx + dy + 2] = 0;
          }
      }
      memcpy(surface-&gt;pixels, pixels.data(), surface-&gt;pitch * surface-&gt;h);
      SDL_UnlockSurface(surface);
  }
  </code></pre>
  
  <p>It works, but when testing it by converting the modified surface to a texture using <code>SDL_CreateTextureFromSurface</code> and copying the texture to the screen, it only displays one green pixel:</p>
  
  <p><a href="https://i.stack.imgur.com/h7If3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h7If3.png" alt="window screenshot"></a></p>