我有以下代码,其中包含未排序的歌曲和艺术家列表,并对它们进行排序和显示。

int main()
{
   SongList totalList; // has a public 2d array 'unsortedSongs' variable
   char songs[100][80] =
   {
      {"David Bowie 'Ziggy Stardust'",},
      {"Smokey Robinson 'You've Really Got A Hold On Me'",},
      {"Carole King 'You've Got A Friend'",},
      // many more songs here totaling to 100
      {"Joni Mitchel 'A Case Of You'",},
      {"Prince 'Kiss'"}

   };
   memcpy(&totalList.unsortedSongs, &songs, sizeof(songs)); // this causes a segmentation fault
   totalList.displaySortedList();
   return 0;
}

我几乎直接从示例here中删除了memcpy的代码,因此我对为什么它不起作用感到困惑。有人可以帮我解决这个问题吗?

编辑:

这是SongList的初始化
class SongList
{
public:
   char unsortedSongs[100][80];
public:
   void displaySortedList();
   void sortList();
   string rearrange(char[]);
   string getSongsForArtist(int*);
};

最佳答案

这行:

memcpy(&totalList.unsortedSongs, &songs, sizeof(songs));

应该:
memcpy(totalList.unsortedSongs, songs, sizeof(songs));

因为songstotalList.unsortedSongs都将decay指向与您引用的引用中的第一个示例类似的指针:
memcpy ( person.name, myname, strlen(myname)+1 );

10-01 05:24
查看更多