title: Deep Copy of a struct with another struct pointer
body: <p>I am trying to copy the contents of one struct to another temp struct so i can alter the RGB pixels of the temp struct without affecting the outcome (if i altered the global pixels instead).</p>
  
  <p>Code
   Structs</p>
  
  <pre><code>//the pixel structure
  typedef struct {
      GLubyte r, g, b;
  } pixel;
  
  //the global structure
  typedef struct {
      pixel *data;
      int w, h;
  } glob;
  glob global, original, temp;
  </code></pre>
  
  <p>my copy Code</p>
  
  <pre><code>void copyPic(glob *source, glob *dest){
      int x,y;
      dest -&gt; w = source -&gt; w;
      dest -&gt; h = source -&gt; h;
      dest -&gt; data = (pixel *) malloc(dest-&gt;w * dest-&gt;h * sizeof(pixel*));
      for (x=0; x &lt; dest -&gt; w; x++)
          for (y=0; y &lt; dest -&gt; h; y++){
              memcpy(dest-&gt;data[x+y*dest-&gt;w], source-&gt;data[x+y*dest-&gt;w], sizeof(pixel))
  
          }
  
  }
  </code></pre>
  
  <p>The idea: the glob struct holds the image width, height and pixel* data which is a pointer to an array of R,G,B values.</p>
  
  <p>I want to copy the global to temporary so when i change the RGB of temp->data it doesnt affect the code that is currently executing and basing changing the RGB off the RGB of global->data.</p>
  
  <p>New Code</p>
  
  <pre><code>void copyPic(glob *src, glob *dest){
  
  dest -&gt; w = src -&gt; w;
  dest -&gt; h = src -&gt; h;
  dest -&gt; data = (pixel *) malloc(dest-&gt;w * dest-&gt;h * sizeof(pixel));
  
  memcpy(dest-&gt;data, src-&gt;data, sizeof(pixel) * dest-&gt;w  * dest-&gt;h);
  </code></pre>
  
  <p>}</p>
  
  <p>Do i have to free anything?</p>