2014-09-26 83 views
-3

對不起,我是一名全新的C++和編程新手,我收到了堆損壞錯誤。我認爲我寫在未分配的內存中,但我似乎無法找到錯誤在哪裏......該程序是soppuse採取用戶輸入值並重新排列它們,以便他們將提升。我也在學習模板。由於陣列使用情況,檢測到堆損壞

#include <iostream> 
#include <iomanip> 
#include <cmath> 

using namespace std; 

template <typename T> 
void sort(T arrayz[], int size, char ch) 
{ 
    T temporary; 
    int k, j; 

    if (ch = 'a') 
    { 
     for (k = 0; k < size; k++) 
     { 
      for (j = 0; j < size; j++) 
      { 
       temporary = arrayz[j]; 
       arrayz[j] = arrayz[j + 1]; 
       arrayz[j + 1] = temporary; 
      } 
     } 
    } 
} 

int main() 
{ 
    int choices, range, i; 
    int x; 
    char ch; 

    cout << ("Enter the amount of numbers you want =>"); 
    cin >> x; 

    int *numbers = new int[x]; 
    if (!numbers) 
    { 
     cout << "Memory Allocation error!"; 
     cin.get(); 
     exit(1); 
    } 

    for (int i = 0; i<x; i++) 
    { 
     cout << "Option number" << i + 1 << " =>"; 
     cin >> numbers[i]; 
    } 

    cout << "Do you want ascending or descending values (a/d) =>" ; 
    cin >> ch; 

    if (ch = 'a') 
    { 
     sort(numbers, x, ch); 
    } 

    else if (ch = 'd') 
    { 
     sort(numbers, x, ch); 
    } 

    delete[] numbers; 
    fflush(stdin); 
    cin.get(); 

    return 0; 
} 
+1

分配給arrayz [j + 1]會損壞堆,for循環有一個錯誤的錯誤。 Google「c泡泡排序」。 – 2014-09-26 02:45:14

+0

'if(ch ='a')'這應該是'if(ch =='a')' – PaulMcKenzie 2014-09-26 03:41:11

+0

Whyz你把z添加到你的wordz的最後? – 2014-09-26 03:55:16

回答

1

在你sort功能,你是在指數j + 1訪問元素。但是,這是超出界限的。 arrayz陣列的有效索引是0size-1。當jsize-1,j+1size,它訪問數組的末尾。