为什么我会收到断言错误?

发布于 2024-08-14 03:57:55 字数 562 浏览 3 评论 0原文

#include <iostream>
using namespace std;

int main ()
{
 int size = 0;
 int* myArray = new int [size + 1];
 cout << "Enter the exponent of the first term: ";
 cin >> size;
 cout << endl;
 for (int i = size; i >= 0; --i)
 {
  cout << "Enter the coefficient of the term with exponent " 
   << i << ": ";
  cin >> myArray[i];
 }
 for (int i = size; i >= 0; --i)
 {
  cout << i << endl;
 }
 return 0;
}

为什么输入大于 2 时会出现断言错误?这是多项式程序的前身,其中数组的下标是每一项的幂,而 array[下标] 处的元素是系数。

#include <iostream>
using namespace std;

int main ()
{
 int size = 0;
 int* myArray = new int [size + 1];
 cout << "Enter the exponent of the first term: ";
 cin >> size;
 cout << endl;
 for (int i = size; i >= 0; --i)
 {
  cout << "Enter the coefficient of the term with exponent " 
   << i << ": ";
  cin >> myArray[i];
 }
 for (int i = size; i >= 0; --i)
 {
  cout << i << endl;
 }
 return 0;
}

Why am I getting an assertion error on input greater than 2? This is the precursor to a polynomial program where the subscript of the array is the power of each term and the element at array[subscript] is the coefficient.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浪推晚风 2024-08-21 03:57:55

您的数组被分配为 int[1]。它需要在您读取大小值之后分配。

Your array is allocated to be an int[1]. It needs to be allocated after you read in the size value.

天煞孤星 2024-08-21 03:57:55

当 size = 0 时,您正在初始化数组,数组大小为 1
当超出数组边界 (1) 时,您会收到断言错误。

You are initializing your array when size = 0, giving an array size of 1
You get your assertion error when you go outside of the array bounds (1).

终陌 2024-08-21 03:57:55

myArray 的大小始终为 0 + 1 = 1。 i 从用户输入的任何内容开始,您进行的第一个数组访问是 myArray[i]。因此,假设用户输入 5,您的数组大小为 1,并且您访问 myArray[5]。它会失败!

我会在输入大小后分配数组。

myArray always has size 0 + 1 = 1. i starts out at whatever the user inputted, and the first array access you make is myArray[i]. So, say the user inputs 5, your array has size 1 and you access myArray[5]. It will fail!

I would allocate the array AFTER you input size.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文