title: bmp image to matrix (2d array) in c
body: <p>I need to put a bmp (RGB 24 bit) image into a 2D array, using the C language.
  I have written some functions, but those functions work only with square images.
  I have created this structure to store the pixels:</p>
  
  <pre><code>typedef struct{
  int red;
  int green;
  int blue;
  }pixel;
  </code></pre>
  
  <p>I have also created two int extern values Y and X to store height and width of the image.
  This is the code (I omitted the setWidthHeight and CreateNewImage functions because I'm sure they work)</p>
  
  <pre><code>int X, Y;
  
  int bitmapin(FILE* fp,/* int height, int width, */ pixel** img1){
      long n;
      int t;
      fseek(fp, 10, SEEK_SET);
      fread(&amp;t, 1, 4, fp);            //reads the offset and puts it in t
      fseek(fp, t, SEEK_SET);         
      int i, p, e;
      e=4-((X*3)%4);
      if (e==4) {
          e=0;
      }
      for (i=Y-1; i&gt;=0; i-- ) {
          for (p=0; p&lt;X; p++) {
              n=fread(&amp;img1[i][p].blue, 1, 1, fp);
              if (n!=1) {
                  return 29;
              }
              n=fread(&amp;img1[i][p].green, 1, 1, fp);
              if (n!=1) {
                  return 30;
              }
              n=fread(&amp;img1[i][p].red, 1, 1, fp);
              if (n!=1) {
                  return 31;
              }
          }
          fseek(fp, e, SEEK_CUR);
      }
      return 0;
  }
  
  pixel** make2Dpixelarray(/*int y, int x*/){
      pixel** theArray;
      theArray=(pixel**) malloc(X*sizeof(pixel*));
      for (int i=0; i&lt;X; i++) {
          theArray[i]=(pixel*) malloc(Y*sizeof(pixel));
      }
      return theArray;
  }
  
  
  
  int main(int argc, const char * argv[]) {
     FILE* fp;
      fp=fopen("/Users/admin/desktop/Immagine5.bmp", "r");
      if (fp==NULL) {
          return 20;
      }
      setWidthHeight(fp);               //Puts X=width and Y=height, it works
      pixel** img1=make2Dpixelarray();  //Creates 2D pixel array and get the memory for it
      bitmapin(fp, img1);               //this function should put the values of RGB pixel into the matrix
      CreateNewImage(fp, img1);        //This function creates a new image.
      return 0;
  }
  </code></pre>
  
  <p>When the image is square there are no problems but when:</p>
  
  <ul>
  <li>height>width: I get the error "BAD_ACCESS..." when i try to read the first pixel in bitmapin()</li>
  <li>width>height: The first line of pixel is OK. But the left side is a kind of copy of the right side with much more blue and very little green.</li>
  </ul>
  
  <p>Could someone help me solving this problem?</p>