首页 > 解决方案 > 运行时检查失败 #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;
}

标签: c++

解决方案


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

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

推荐阅读