要求在堆空间分配5个整型变量空间,分别存放100,200,300,400,500,要求把这个五个数倒序输出,即输出500,400,300,200,100。(要求使用new和delete操作符分配和回收堆空间)下面程序错那了?

#include
int main()
{
int arraysize,t,j;
int *array;
cout<<"please input a number of array elements:\n";
cin>>arraysize;
if((array=new int[arraysize])==NULL)
{
cout<<"can't allocate more memory,terminating.\n";
exit(1);
}
for(int count=0;count array[count]=count+100;
for(int i=0;i {
for(int j=0;j {
if(array[j]>array[j+1])
{
t=array[j];
array[j]=array[j+1];
array[j+1]=t;
}
}
}
cout<<array[j]<<" "<<endl;
delete[]array;
return 0;
}

for(int count=0;count array[count]=count+100;
for(int i=0;i {
for(int j=0;j {
这里都不对

完整给你写一个

#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int * arr = new int[n];
if (!arr)
{
cout << "error on alloc";
return;
}
for (int i = 0; i < n; i++) cin >> arr[i];
for (int i = n - 1; i >= 0; i--) cout << arr[i] << " ";
delete[] arr;
return 0;
}

你的算法没有问题,基本上都是语法上的错误。建议参考以下代码(也是你的源代码简化版):


#include <iostream>
using namespace std;

int main()
{
    int arraysize, j;
    int *array;

    cout<<"please input a number of array elements:\n";
    cin>>arraysize;

    // 申请堆空间
    if ((array=new int[arraysize])==NULL)
    {
        cout<<"can't allocate more memory,terminating.\n";
        exit(1);
    }

    // 按 100,200,300,400,500 顺序存入array
    for ( j=0; j<arraysize; )
        array[j]=(++j) * 100;

    // 按 100,200,300,400,500 倒序输出
    for ( ; j; )
        cout<<array[--j]<<" ";
    cout<<endl;

    // 回收堆空间
    delete [] array;

    return 0;
}