求教,关于c++动态数组释放内存的问题
影湛_SK 2012-05-05 02:47:22 #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void ProduceRandomString(int* &X, int* &Y, const int &xl, const int &yl)
{
srand((unsigned)time(NULL));
for(int i = 0; i < xl; i++)
{
if(rand()&1) X[i] = 1;
else X[i] = 0;
}
for(int j = 0; j < yl; j++)
{
if(rand()&1) Y[j] = 1;
else Y[j] = 0;
}
}
void getNext(const int* &a, int* &next, const int length)
{
int i = 0;
int j = -1;
next[0] = -1;
while(i < length)
{
if(j == -1 || a[i] == a[j])
{
++i;
++j;
if(a[i] != a[j]) next[i] = j;
else next[i] = next[j];
}
else
{
j = next[j];
}
}
}
bool KMP(const int* &X, const int* &Y, const int &xl, const int &yl)
{
int *next = new int[yl];
getNext(Y, next, yl);
int i = 0;
int j = 0;
while(i < xl && j < yl)
{
if(j == -1 || X[i] == Y[j])
{
i++;
j++;
}
else
j = next[j];
}
// delete [] next;////----------------------为什么加上这句就会报错
if(j == yl)
return true;
else
return false;
}
int main()
{
int *X = new int[100];
int *Y = new int[9];
int c = 20;
while(c--)
{
ProduceRandomString(X, Y, 100, 9);
for(int i = 0; i < 100; i++)
cout << *(X+i);
cout << endl;
for(int j = 0; j < 9; j++)
cout << *(Y+j);
cout << endl;
if(KMP(X, Y, 100, 9))
cout << "匹配";
else cout << "不匹配";
cout << endl;
for(int k = 0; k < 100000000; k++)
;
}
return 0;
}