c++ - 运行时检查失败 #2 - 变量“sortObject”周围的堆栈已损坏。怎么修?
问题描述
我试图将数字存储在数组中。数组的前半部分是按 1、2、3、4、5 等递增的数字,数组的后半部分是随机数。当我运行程序时,它会产生我想要的输出但给我错误请帮助
#include <iostream>
#include <cstdlib>
using namespace std;
class sorting {
private:
int size, elements;
int arr[NULL];
public:
void sort(){
cout << "Enter number of desired elements" << ">"; cin >> elements;
arr[elements];
half();
}
void half() {
for (int i = 0; i < elements/2; i++) {
arr[i] = i + 1;
}
for (int i = elements / 2; i < elements; i++) {
arr[i] = rand();
}
cout << "This is the elements of the array";
for (int i = 0; i < elements; i++) {
cout << arr[i] << " ";
}
}
};
int main()
{
sorting sortObject;
sortObject.sort();
return 0;
}
解决方案
正如我所看到的,您希望数组大小在运行时根据输入而改变,我们需要动态分配一个数组。所以将整数指针作为字段而不是静态数组。然后在读取输入后的排序函数内部,动态地将内存分配给指针。(实际上,如果我们在构造函数中这样做会更好)。
int *arr;
arr=(int *)malloc(elements*sizeof(int));
推荐阅读
- angular - 如果模态中有未保存的更改,如何防止取消模态?
- sprite-kit - 使 SKLabelNode 不透明背景的简单方法?
- debian - Debian/Ubuntu Java 11 java-alternative
- php - 错误:需要支持 FreeType 的 GD PHP 扩展或支持 PNG 的 ImageMagick PHP 扩展
- javascript - 如何在 html 中的元素之前添加单数关闭 div '
- xslt - 在 XSLT 中实现动态 xpath:for-each-group
- python - 如何与 modelica 模型进行联合仿真?
- naming-conventions - 您如何将超时前的最小秒数描述为变量?
- javascript - 重新部署 Web 应用程序会导致看似随机的 JavaScript 函数和对象未定义
- acumatica - 在自定义 DAC 的选择器上启用“AllowAddNew”和/或“AllowEdit”