返回信息流谢谢大家,问题已结!
是在new时出错了,开辟的数组空间小了~
下面是Shell排序代码,在VC6.0环境中运行能出正确结果,但整个程序在“delete a”(倒数第二句)处有问题,前面有“a = new int[num];”,百思不得其解,感觉没错啊。。。
请教达人,谢谢!!!
#include <iostream.h>
void shell_sort (int *a, int n);
void shell_insert (int *a, int n, int d);
int main()
{
int num;
int *a;
cout << "Pls input the total number you want to sort:";
cin >> num;
a = new int[num];
a[0] = 0; //array[0] is not used
cout << "Pls input every element the array contains.\n";
for (int i=1; i<=num; i++){
cout << "the element " << i << " is:";
cin >> a[i];
}
shell_sort (a, num);
cout << "The result is:\n";
for (i=1; i<=num; i++){
cout << a[i] << " ";
}
cout << endl;
delete a; //运行到此出错,很纳闷????
return 0;
}
void shell_sort (int *a, int n)
{
for (int k=n/2; k>0; k--){
shell_insert (a, n, k);
}
}
void shell_insert (int *a, int n, int d) // "d" is the current increment
{
int group, i, j;
for (group=1; group<=d; group++){
for (i=d+group; i<=n; i=i+d){
if (a[i]<a[i-d]){
a[0] = a[i];
j = i-d;
do{
a[j+d] = a[j];
j -= d;
} while (j>0 && a[j]>a[0]);
a[j+d] = a[0];
}
}
}
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #8583同步于 2008/6/19
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
[请教:] 一个关于delete的疑问
tracy85
2008/6/19镜像同步8 回复
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
写成“delete a[]”后编译就出错:
error C2059: syntax error : ']'
也试过“delete []a”,同样运行到此出错。。。
【 在 rebirthatsix 的大作中提到: 】
: delete a[];
出错信息贴一下。。
【 在 tracy85 (tracy) 的大作中提到: 】
: 写成“delete a[]”后编译就出错:
: error C2059: syntax error : ']'
: 也试过“delete []a”,同样运行到此出错。。。
: ...................
re
a = new int[num + 1];
....
delete []a;
【 在 PtwCJ (鲜的每日C|头像不是我,我是长毛贼~~) 的大作中提到: 】
: 数组开的不够大吧?
: num+1
谢谢,还真是这个问题!
没考虑到使用数组的下标是从1开始,呵呵
不过为什么在使用时反而没报错,而在删除时出错了呢?
【 在 PtwCJ 的大作中提到: 】
: 数组开的不够大吧?
: num+1