title: Dynamically allocate 2-dimensional structure array in C
body: <p>I have been trying to create an edges filter as per CS50 problem set 4. I have seen several solutions, however I would like to know if my approach can work. I'm trying to expand the input image by a black border of one pixel width. For this I want to expand my two-dimensional RGBTRIPLE structure by one pixel on either side. I am setting all values of RGB to 0 (aka black) in the first line and then copy the original image into the temporary structure, substituting all except the border values with the respective colours.</p>
  <p>I am defining a variable-length two-dimensional structure RGBTRIPLE which contains three values of the datatype BYTE:</p>
  <pre><code>RGBTRIPLE temp[height+2][width+2] = {};
  </code></pre>
  <p>I'm getting the error message that because of the variable length it may not have been initialized, which I understand. I have seen several solutions using pointers and <strong>malloc</strong>, which I hopefully implemented correctly in the first line. I have been trying to connect the RGBTRIPLE to the pointer as per the following two lines:</p>
  <pre><code>RGBTRIPLE *ptr = (RGBTRIPLE *)malloc((height+2)*(width+2)*sizeof(RGBTRIPLE));
  RGBTRIPLE temp[height+2][width+2] = &amp;ptr;
  temp[height+2][width+2] = {0};
  </code></pre>
  <p>Setting all the values to zero here does also not work, but that's another issue.</p>
  <p>I want to use the original RGBTRIPLE in a <strong>for-loop</strong> and I cannot get this to work. All examples I have seen use the pointers afterwards to add any information. Is there any way to define the RGBTRIPLE using malloc so that I can afterwards use it in code as a &quot;normal&quot; element of the structure as seen with <strong>temp[][]</strong>:</p>
  <pre><code>for(int i = 0; i &lt; height; i++)
  {
      for(int j = 0; j &lt; width; j++)
      {
          temp[i+1][j+1] = image[i][j];
      }
  }
  
  for(int i = 1; i &lt;= height; i++)
  {
      for(int j = 1; j &lt;= width; j++)
      {
          int counter = 0;
          float gxr, gxb, gxg, gyr, gyb, gyg = 0;
  
          //right pixel
          gxb += (2*temp[i][j+1].rgbtBlue);
          gxg += (2*temp[i][j+1].rgbtGreen);
          gxr += (2*temp[i][j+1].rgbtRed);
  </code></pre>
  <p>etc. for all surrounding pixels.</p>
  <p>Any help is appreciated.</p>