我试图将数字存储在数组中。数组的前半部分是按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;
}
最佳答案
如我所见,您希望数组大小在运行时根据输入而变化,因此我们需要动态分配数组。因此将整数指针作为字段而不是静态数组。
然后在读取输入后在sort函数内部,将内存动态分配给指针。(实际上,如果在构造函数中进行操作则更好)。
int *arr;
arr=(int *)malloc(elements*sizeof(int));
关于c++ - 运行时检查失败#2-变量 'sortObject'周围的堆栈已损坏。怎么修?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64409928/