2014-09-26 80 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,它访问数组的末尾。