title: C - Add an element to a struct pointer
body: <p>Im trying to add a a struct Song to my struct pointer song* but when trying to write it to a file it just gives out junk.
  This is my function:</p>
  
  <pre><code>void addSong(Song *song, char songName[], char artistName[], int publicationYear, int *nrOfSongs)
  {
      Song *tempSongs = (Song*)malloc(sizeof(Song)*(*nrOfSongs));
  
      for (int i = 0; i &lt; (*nrOfSongs); i++)
          {
              strcpy(tempSongs[i].artistName, song[i].artistName);
              strcpy(tempSongs[i].songName, song[i].songName);
              tempSongs[i].publicationYear = song[i].publicationYear;
          }
  
      free(song);
      *nrOfSongs = (*nrOfSongs) + 1;
      song = (Song*)malloc(sizeof(Song)*(*nrOfSongs));
  
  
      for (int i = 0; i &lt; ((*nrOfSongs)-1); i++)
          {
              strcpy(song[i].artistName, tempSongs[i].artistName);
              strcpy(song[i].songName, tempSongs[i].songName);
              song[i].publicationYear = tempSongs[i].publicationYear;
          }
  }
  </code></pre>
  
  <p>Edit 1: Sorry for the bad question.</p>
  
  <p>My function writeToFile:</p>
  
  <pre><code>void writeToFile(char fileName[], Song *song, int *nrOfSongs)
  {
      char name[256];
      snprintf(name, sizeof(name), "%s.txt", fileName);
      FILE * file = fopen(name, "w");
  
      fprintf(file, "%d", *nrOfSongs);
      fputc('\n', file);
  
      for (int i = 0; i &lt; (*nrOfSongs); i++)
      {
          fputs(song[i].songName, file);
          fputs(song[i].artistName, file);
          fprintf(file, "%d", song[i].publicationYear);
          fputc('\n', file);
      }
  
      fclose(file);
  }
  </code></pre>
  
  <p>An example of a file:</p>
  
  <pre><code>4
  Mr Tambourine Man
  Bob Dylan
  1965
  Dead Ringer for Love
  Meat Loaf
  1981
  Euphoria
  Loreen
  2012
  Love Me Now
  John Legend
  2016
  </code></pre>
  
  <p>I want to add a song and by that i want to add an artistName, songName and publicationYear to my struct pointer and then write the struct pointer to a new file.</p>