title: Struct with 2d array segmentation fault's on writing
body: <p>I have been having trouble with this function the past day, and scouring similar questions in the website did not help.</p>
  
  <p>I am trying to initialize a struct which contains a 2d array. As is, the program compiles fine and has no problem reading from the array, but causes a segmentation fault every-time it tries to write to the array.</p>
  
  <p>This is the structure in question:</p>
  
  <pre><code>typedef struct {
      pgm_format_t format;
      unsigned int width;
      unsigned int height;
      unsigned int block_width;
      unsigned int block_height;
      unsigned int max_value;
      unsigned short **blocks;
  } cod_t;
  </code></pre>
  
  <p>And this is the function:</p>
  
  <pre><code>cod_t cod_create(pgm_format_t format, unsigned int width, unsigned int height){
  
  cod_t cod;
  unsigned short i;
  
  if((cod.blocks=calloc(width,sizeof(unsigned short *)))==NULL){
  
  printf("nope 1\n"); //no problem
  }
  
  for(i=0;i&lt;width;i++){
      if((cod.blocks[width]=calloc(height,sizeof(unsigned short)))==NULL){
          printf("nope 2\n"); //no problem
      }
  }
  int f=cod.blocks[0][0]; //no problem
  printf("%d",f); //writes a wierd number, probably because it's never been assigned
  
  cod.blocks[0][0]=3; //segmentation fault
  printf("%d",cod.blocks[0][0]);
  
  return cod;
  }
  </code></pre>
  
  <p>What am I doing wrong here?</p>
  
  <p>EDIT:</p>
  
  <p>Ok, it appears I made a newbie mistake in the second calloc. however, even with</p>
  
  <pre><code>    if((cod.blocks[i]=calloc(height,sizeof(unsigned short)))==NULL){
  </code></pre>
  
  <p>the second printf prints something other than 3 (in my case, 031280), so there is something still wrong about this.</p>
  
  <p>There is no segmentation fault now though (not in this part of the program at least, though there is one further away, when it tries to write several numbers to the array).</p>