2014-03-06 11 views
2

我是C++的新手,目前正在開發一個關於我的C++類中動態分配的項目。我不能爲我的生活弄清楚我在這個程序中的指針出錯的地方。我正在使用三種不同的.cpp文件,我們應該製作一個基本的播放列表程序。試圖找出我用指針(C++)所犯的錯誤

請不要給我提示任何其他亂碼我得去,我只是想弄清楚的指針:

(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程序)

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循環來保持菜單繼續),我得到一個錯誤。謝謝!讓我知道你是否需要更多關於任何功能的信息。

+1

'newlist [size]'? – chris

回答

4

變化:

newlist[size] = *s; 

要:

newlist[size-1] = *s; 
+0

天啊!非常簡單!感謝您的幫助,哈哈。 – user1888527

+0

不客氣:) –

3

有兩個可能的問題:

  • 你的任務總是出界。要訪問數組的最後一個元素,您必須始終使用newlist[size - 1]而不是newlist[size],因爲第一個元素始終位於C/C++中的索引0處。

  • 由於您在嘗試使用delete [] list;刪除它之前沒有驗證您是否有舊列表,因此您必須確保您的指針最初設置爲NULL或者有一些初始(有效)指針分配給它確實可以刪除。