簡體   English   中英

運行時檢查失敗 #2 - 變量“sortObject”周圍的堆棧已損壞。 怎么修?

[英]Run-Time Check Failure #2 - Stack around the variable 'sortObject' was corrupted. how to fix?

我試圖將數字存儲在數組中。 數組的前半部分是按 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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM