一个莫名其妙的delete错误,请大大门指点一二
刚刚写了个shell排序的程序,在最后delete指针的时候莫名奇妙的出错了,各位帮忙看看到底是怎么回事。程序源代码如下:
程序代码:
#include <iostream> #include <time.h> #include <stdlib.h> using namespace std; const int len = 15; int switch_num = 0; int* CreateArray(int n) { int* p = new int[n]; *(p+0) = 26; *(p+1) = 78; *(p+2) = 39; *(p+3) = 60; *(p+4) = 30; *(p+5) = 87; *(p+6) = 30; *(p+7) = 57; *(p+8) = 55; *(p+9) = 6; *(p+10) = 41; *(p+11) = 19; *(p+12) = 62; *(p+13) = 49; *(p+14) = 40; return p; } int* CreateRandomArray(int n) { srand(time(NULL)); int* p = new int[n]; for (int i = 0; i < n; ++i) { p[i] = rand() % 100; } return p; } int* CopyArray(int* p, int n) { int i; int* pArr = new int[n]; for (i = 0; i < n; ++i) { pArr[i] = p[i]; } return pArr; } void PrintArray(int* p, int n) { int i; for (i = 0; i < n; ++i) { cout << p << " "; } cout << endl; } void Switch(int& a, int& b) { a = a ^ b; b = a ^ b; a = a ^ b; } ////////////////////////////////////////////////////////////////////// //希尔排序 void ShellSort(int* p, int n) { int i, j, k; for (int gap = n / 2; gap > 0; gap = gap / 2) { for (k = 0; k < gap; ++k) { for (i = k + gap; i < n; i += gap) { for (j = i; j > 0; j -= gap) { if (p[j] < p[j-gap]) { Switch(p[j], p[j-gap]); ++switch_num; } else { break; } } } } PrintArray(p, n); } } ////////////////////////////////////////////////////////////////////// int main() { cout << "Hello world!" << endl; srand(time(NULL)); int* pArr; cout << "before sort: " << endl; pArr = CreateArray(len); //pArr = CreateRandomArray(len); PrintArray(pArr, len); cout << endl << endl; switch_num = 0; int* pArrShell = CopyArray(pArr, len); ShellSort(pArrShell, len); cout << "after shell sort:" << endl; PrintArray(pArrShell, len); cout << "switch number is: " << switch_num << endl << endl; delete[] pArrShell; //就是在这个位置出错的 delete[] pArr; return 0; }
[ 本帖最后由 flashboy84 于 2011-8-22 00:52 编辑 ]