试图找出我用指针犯下的错误(C ++)

时间:2014-03-06 23:19:20

标签: c++ pointers dynamic-allocation

我是C ++的新手,目前正致力于一个关于C ++类动态分配的项目。我不能为我的生活找出我在这个程序中指针错误的地方。我有三个不同的.cpp文件我正在使用,我们应该制作一个基本的播放列表程序。

请不要给我任何其他任何凌乱的代码提示,我只是想弄清楚指针:

(Playlist class, contains a dynamic array of songs)
    Playlist::Playlist (int s) {
       size = s;
       list = new Song[size];
    }

Playlist::~Playlist() {
   delete [] list;
}

void Playlist::Add(Song * s) {

   size++;

  Song * newlist = new Song[size];

  for(int i = 0; i < size - 1; i++) {
     newlist[i] = list[i];
  }

  delete [] list;

  newlist[size] = *s;
  list = newlist;
}

(菜单程序)

switch (choice) {
  case 'A': {
     cout << "\nEnter a song title to add: ";
     cin.getline(tempTitle,36);
     cout << "Enter the artist's name: ";
     cin.getline(tempArtist,20);
     cout << "Enter the category of the song ([P]op, [R]ock, [A]lternative, [C]ountry, [H]ip Hop, or Parod[Y$
     cin >> catStorage;
     tempCat = StyleChoice(catStorage);
     cout << "Enter the size of the song in kilobytes: ";
     cin >> tempSize;

     Song * tempS = new Song;
     tempS->Set(tempTitle, tempArtist, tempCat, tempSize);
     mainlist.Add(tempS);
     delete tempS;

     break;
   }

每当我运行Add()函数然后退出菜单程序时,我都会收到错误(我有一个“X”条件,结束了保持菜单运行的while循环)。谢谢!如果您需要有关任何功能的更多信息,请与我们联系。

2 个答案:

答案 0 :(得分:4)

变化:

newlist[size] = *s;

要:

newlist[size-1] = *s;

答案 1 :(得分:3)

有两个可能的问题:

  • 您的作业总是不受限制。要访问数组的最后一个元素,您将始终必须使用newlist[size - 1]而不是newlist[size],因为第一个元素始终位于C / C ++中的索引0

  • 由于在尝试使用delete [] list;删除之前未验证是否有旧列表,因此您必须确保指针最初设置为NULL或者指定了一些确实可以删除的初始(有效)指针。