title: Structs in C Programming
body: <p>I'm trying to read a files contents and store them in to a struct for some reason I keep getting segmentation fault. Help me please, I don't understand valgrind much either.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef struct {
      int day;
      int month;
      int year;
      char text[401];
  } journal;
  
  int main(int argc, char** argv){
      int  i, numberEntries;
      FILE* fp = fopen(argv[1], "r");
  
      fscanf(fp,"%d", &amp;numberEntries); /* reads value on first line of file for number of entries */
      printf("%d", numberEntries); /* check that it worked */
      journal *entryArray ;
      entryArray = (journal*)malloc(sizeof(journal));
  
      if(fp == NULL){
          perror("Error opening file");
      } else {
  
          for(i=0; i&lt;4; i++){
              fscanf(fp,"%d/%d/%d", entryArray[i].day, entryArray[i].month, entryArray[i].year);
              fgets(entryArray[i].text, 400, fp);
              printf("%s", entryArray[i].text);
          }
      } 
      for(i=0; i&lt;4; i++){
          printf("%d %d %d", entryArray[i].day, entryArray[i].month, entryArray[i].year);
          printf("%s", entryArray[i].text);
      }
      free(entryArray);
      return 0;
  }
  </code></pre>
  
  <p>Updated code: still gives segmentation fault.</p>
  
  <pre><code>typedef struct {
      int day;
      int month;
      int year;
      char text[401];
  } journal;
  
  int main(int argc, char** argv){
      int  i, numberEntries;
      FILE* fp = fopen(argv[1], "r");
  
      if(fp == NULL){
          perror("Error opening file");
      } else {
          fscanf(fp,"%d", &amp;numberEntries); /* reads value on first line of file for number of entries */
          printf("%d", numberEntries); /* check that it worked */
          journal *entryArray ;
          entryArray = (journal*)malloc(numberEntries*sizeof(journal));
          for(i=0; i&lt;4; i++){
              fscanf(fp,"%d/%d/%d", &amp;entryArray[i].day, &amp;entryArray[i].month, &amp;entryArray[i].year);
              fgets(entryArray[i].text, 400, fp);
              printf("%s", entryArray[i].text);
          }
          for(i=0; i&lt;4; i++){
              printf("%d/%d/%d", entryArray[i].day, entryArray[i].month, entryArray[i].year);
              printf("%s", entryArray[i].text);
          }
          free(entryArray);
      } 
      return 0;
  }
  </code></pre>
  
  <p>Input file</p>
  
  <pre><code>4
  12/04/2010
  Interview went well I think, though was told to wear shoes.
  18/04/2010
  Doc advised me to concentrate on something... I forget.
  03/05/2010
  Was asked today if I was an art exhibit.
  19/05/2010
  Apparently mudcakes not made of mud, or angry wasps.
  </code></pre>