数组和指针 + 错误

时间:2021-07-17 00:18:21

标签: c++ arrays pointers

任务如下:

<块引用>

您的目标是编写一个程序,以相反的顺序显示输入中的一系列整数。您的 程序将提示用户输入此列表中的值的数量,它将用作动态的大小 在此提示之后声明的数组。

数组 size 未知,value 是指针,sub 必须在循环之前赋值。

以下是步骤:

  1. 声明变量,但不要“为指针分配内存”。在提示用户输入值后执行此操作。
  2. 提示用户输入要列出的值的数量。 (如果用户输入数字,则必须向用户发送一条消息)。然后使用关键字 new 作为指针。
  3. 提示用户输入值
  4. 反向显示值。
  5. 对动态数组使用关键字 delete

当我试图运行程序时,错误是:

<块引用>

错误:ISO C++ 禁止指针和整数之间的比较 [-fpermissive]
for(int sub = 0; sub < size; size--)
------------------------------^
错误:需要左值作为递减操作数
for (int sub = 0; sub > size; size--)
-------------------------------------------------- ----^

另外,我不确定关键字 new 的作用。

#include <iostream>
using namespace std;

int main()
{
    int size, array;

    cout << "How many values would you like to enter? ";
    cin >> array;
    
    
    int value;
    int *array = new int[size];
    
    if (size > 0)
    {
        for (int sub = 0; sub < size; size++)
        {
            cout << "Enter value #" << size << ": ";
            cin >> value;
        }
        while (size > 0);
    }
    
    else
    {
        while (size < 0)
        {
            cout << "Size must be positive." << endl;
            cout << "How many values would you like to enter? ";
            cin >> size;
        }
    }
    
    cout << "Here are the values you entered in reverse order: \n";
    
    for (int sub = size - 1; sub >= 0; size--) 
    {
        cout << "Value #" << size << " :" << value << endl;
    }
    
    delete[] array;

    return 0;
}

PS:我知道 size 应该是未知的,但我遇到了另一个错误说

<块引用>

“size”的存储大小未知

因此,我添加数字以避免该错误。

编辑:感谢@MikeCAT,我更改了代码,但此错误显示terminate called after throwing an instance of 'std::bad_array_new_length what(): std::bad_array_new_length。这是因为我为 size 输入了一个数字,这应该发生在 if 语句中。此外,在用户输入他们想要输入的值后,我需要 size1 开始,但 size 始终从输入的数字开始。< /p>

1 个答案:

答案 0 :(得分:1)

正如作业所说,你应该

  1. 读取值
  2. 使用读取的值作为其大小分配动态数组
  3. 读取数组的数字
#include <iostream>

int main(void) {
    // read a number (size of a dynamic array)
    int numElements;
    std::cin >> numElements;

    // allocate a dynamic array
    int *array = new int[numElements];

    // read values for the dynamic array
    for (int i = 0; i < numElements; i++) {
        std::cin >> array[i];
    }

    // print the values in reversed order
    for (int i = numElements - 1; i >= 0; i--) {
        std::cout << array[i] << '\n';
    }

    // de-allocate the array
    delete[] array;

    // exit normally
    return 0;
}

省略了错误处理和无关紧要的消息。尝试添加它们。

相关问题