c++ - 运行时检查失败#2-变量 'sortObject'周围的堆栈已损坏。怎么修?

标签 c++

我试图将数字存储在数组中。数组的前半部分是按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/

相关文章:

c++ - 数组与 vector : Introductory Similarities and Differences

c++ - 方法指针映射,编译器说它们不接受任何参数

c++ - 为什么这不违反单一定义规则?

c++ - 内联函数

c++ - 在 C++ 中强制执行 NULL 检查

C++ 编辑文本文件?

c++ - 最大 SFML 纹理尺寸

c++ - C : x86 Intel Intrinsics usage of _mm_log2_ps() -> error: incompatible type 'int' ?

c++ - 如何使类不可继承

c++ - 无法将字符串转换为 float