Question

I'm a newbie to C++, currently working on a project on dynamic allocation in my C++ class. I can't for the life of me figure out where I went wrong with pointers in this program. I have three different .cpp files that I'm working with, we're supposed to make a rudimentary playlist program.

Please don't give me tips on any of the other messy code I've got going, I'm simply trying to figure out the pointers:

(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;
}

(Menu program)

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;
   }

I get an error whenever I run the Add() function and then exit the menu program (I have an "X" condition that ends the while loop that keeps the menu going). Thanks! Let me know if you need more information on what any of the functions do.

Was it helpful?

Solution

Change:

newlist[size] = *s;

To:

newlist[size-1] = *s;

OTHER TIPS

There are two possible issues:

  • Your assignment is always out of bounds. To access the last element of the array, you'll always have to use newlist[size - 1] rather than newlist[size] since the very first element is always at index 0 in C/C++.

  • Since you don't verify that you've got an old list before trying to delete it with delete [] list; you'll have to make sure that your pointer is initially set to NULL or there is some initial (valid) pointer assigned to it that indeed can be deleted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top