【问题标题】:Trying to figure out the mistake I made with pointers (C++)试图找出我用指针犯的错误(C++)
【发布时间】:2014-03-06 23:19:20
【问题描述】:

我是 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 循环)。谢谢!如果您需要有关任何功能的更多信息,请告诉我。

【问题讨论】:

    标签: c++ pointers dynamic-allocation


    【解决方案1】:

    变化:

    newlist[size] = *s;
    

    收件人:

    newlist[size-1] = *s;
    

    【讨论】:

    • 天哪!就是这么简单!谢谢你的帮助,哈哈。
    【解决方案2】:

    有两个可能的问题:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      相关资源
      最近更新 更多