2017-09-16 32 views
-2

我想創建一個程序,它允許動態分配的數組存儲一些整數,如果需要增加最大值,然後顯示未排序和已排序的數組訂購。指針,動態數組和內存泄漏

鏈接到我的完整代碼是在底部。

我遇到的第一個問題是動態分配的數組在第一次增加大小後會失控。相關代碼如下。

while (counter <= arraySize) 
    { 
     cout <<"Please enter an integer number. Use 999999 (six 9's) to stop\n"; 
     if (counter == arraySize)   //If the counter is equal to the size of the array 
     {         //the array must be resized 
      arraySize +=2; 
      int *temp = new int[arraySize]; 
      for (counter = 0; counter < arraySize; counter++) 
      { 
       temp[counter] = arrayPtr[counter]; 
      } 
      delete [] arrayPtr; 
      arrayPtr = temp; 
      counter ++;      //the counter has to be reset to it's original position 
     }         //which should be +1 of the end of the old array 
     cin >> arrayPtr[counter]; 
     if (arrayPtr[counter] == sentinel) 
     { 
      cout << "Sentinel Value given, data entry ending.\n"; 
      break; 
     } 
     counter ++; 
    } 

這會產生意想不到的操作,其中,而不是等待標記值,它只是開始列出內存整數過去的那一點(因爲沒有邊界檢查)。

下一個問題是我的排序功能拒絕運行。我試着對5個值進行測試,程序在達到特定代碼部分時崩潰。

的功能是使用

sorting (arrayPtr); 

調用,但函數本身看起來像這樣:

void sorting (int *arr) 
{ 
    int count = 0, countTwo = 0, tempVal; 

    for (count = 0; arr[count] != 999999; count++)   //I figured arr[count] != 999999 is easier and looks better 
    {              //A bunch of if statements 
     for (countTwo = 0; arr[countTwo] != 99999; countTwo++) 
     { 
      if (arr[countTwo] > arr[countTwo+1]) 
      { 
       tempVal = arr[countTwo]; 
       arr[countTwo] = arr[countTwo+1]; 
       arr[countTwo+1] = tempVal; 
      } 
     } 
    } 
} 

在這個問題上的任何幫助表示讚賞。

鏈接到我的源代碼:

http://www.mediafire.com/file/w08su2hap57fkwo/Lab1_2336.cpp

由於社區的反饋,此鏈接將儘可能長時間地保持活躍。

下面的鏈接是我更正的源代碼。它是註釋爲了更好地突出我犯的錯誤和解決它們的答案。

http://www.mediafire.com/file/1z7hd4w8smnwn29/Lab1_2336_corrected.cpp

+0

除非這是出於教育原因,否則不應該使用raw'new'和'delete'。對於動態數組,std :: vector是更好的選擇。 – ralismark

+0

這是出於教育原因。 –

+1

*這將一直有效,直到我的問題得到解答。* - 然後這個關於SO的問題變得毫無價值,因爲這個鏈接不再存在。 – PaulMcKenzie

回答

0

我可以在代碼中發現的第一個問題是在for循環,其中計數器從0到ARRAYSIZE-1,循環的最後兩個迭代將訪問arrrayPtr出界。

接下來,在if (counter == arraySize)的末尾有一個counter++;這不是必需的,因爲此時counter已經將數組索引爲無界限。

最後,在你的排序函數中,內循環尋找錯誤的值(99999而不是999999),所以它永遠不會停止並跳出界限。爲了防止出現這種錯誤,您應該將sentinel定義爲一個未命名空間中的常量,並通過代碼使用它,而不是鍵入999999(這很容易出錯......)。

+0

我很感激。我還注意到我上傳的代碼有'&arrayptr'作爲函數參數傳遞給我的'sorting(int *)'函數,導致編譯器錯誤。它現在完美地工作。 –