数组内的cout元素bug,错误?

时间:2015-11-03 19:44:30

标签: c++

每次我输入数组中的元素并打印出来时需要帮助,第二个元素给我一个随机数。例如:array [1,2,3] - >打印出:1,55234,3 --->但总是第二个数字。

int main ()
{
    int i,n;
    int * p;
    cout << "How many numbers would you like to type? ";
    cin >> i;
    p = new (nothrow) int[i];

    for (n=0; n<i; n++)
    {
        cout << "Enter number: ";
        cin >> p[n];
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++){
        cout << p[n] << ", ";
        delete[] p;
    } 
    return 0;
}

2 个答案:

答案 0 :(得分:1)

将删除操作符移到循环外

for (n=0; n<i; n++){
    cout << p[n] << ", ";
}

delete[] p;

另外我会添加打印新行字符

for (n=0; n<i; n++){
    cout << p[n] << ", ";
}
cout << endl;

delete[] p;

答案 1 :(得分:0)

打印第一个元素后,您正在删除该数组。你应该在循环结束后删除它