C - 向结构指针添加元素

时间:2017-01-28 13:19:24

标签: c arrays pointers struct

我试图在我的结构指针歌曲*中添加一个结构歌曲但是当试图将它写入文件时它只是给出了垃圾。 这是我的功能:

void addSong(Song *song, char songName[], char artistName[], int publicationYear, int *nrOfSongs)
{
    Song *tempSongs = (Song*)malloc(sizeof(Song)*(*nrOfSongs));

    for (int i = 0; i < (*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 < ((*nrOfSongs)-1); i++)
        {
            strcpy(song[i].artistName, tempSongs[i].artistName);
            strcpy(song[i].songName, tempSongs[i].songName);
            song[i].publicationYear = tempSongs[i].publicationYear;
        }
}

编辑1:对不好的问题抱歉。

我的函数writeToFile:

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 < (*nrOfSongs); i++)
    {
        fputs(song[i].songName, file);
        fputs(song[i].artistName, file);
        fprintf(file, "%d", song[i].publicationYear);
        fputc('\n', file);
    }

    fclose(file);
}

文件示例:

4
Mr Tambourine Man
Bob Dylan
1965
Dead Ringer for Love
Meat Loaf
1981
Euphoria
Loreen
2012
Love Me Now
John Legend
2016

我想添加一首歌,我希望将artistName,songName和publicationYear添加到我的struct指针中,然后将struct指针写入新文件。

1 个答案:

答案 0 :(得分:0)

您应该使用song放大数组realloc(),而不是复制数组两次,只需添加新元素,如下所示:

Song *addSong(Song *song, char songName[], char artistName[], int publicationYear, int *nrOfSongs) {
  *nrOfSongs++;
  song = realloc(song, *nrOfSongs * sizeof *song);
  // Don't forget to do error checking here, realloc() may return NULL

  strcpy(song[*nrOfSongs - 1].artistName, artistName);
  // et cetera

  return song;
}

因为你正在重新分配内存,所以指向数组的指针会改变,所以你必须将新指针返回给调用者,就像@wildplasser所说的那样。

此外,strcpy()是一个不安全的功能。考虑使用更安全的替代方案,例如snprintf()