运行时检查失败 #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;
}

正如我所看到的,您希望数组大小在运行时根据输入而变化,我们需要动态分配数组。因此,将整数指针作为字段,而不是静态数组。然后在sort函数内部读取输入后,将内存动态分配给指针。(实际上,如果我们在构造函数中这样做会更好(。

int *arr;
arr=(int *)malloc(elements*sizeof(int));

相关内容

最新更新