[英]Run-Time Check Failure #2 - Stack around the variable 'IDNumber' was corrupted
[英]Run-Time Check Failure #2 - Stack around the variable 'k' was corrupted
練習:找出1到1000之間的完美數字(完美數字:例如6,因為6 = 1 + 2 + 3),這是我的代碼。
#include<iostream>
using namespace std;
int main()
{
int k[11];
int i, a, n, s;
for (a = 2; a <= 1000; a++)
{
n = 0;
s = a;
for (i = 1; i < a; i++)
if (a%i == 0)
{
n++;
s = s - i;
k[n] = i;
}
if (s == 0)
{
cout << a << " is a perfect number" << endl;
cout << "its factors are:";
for (i = 1; i <= n; i++)cout << k[i] << " ";
cout << endl;
}
}
return 0;
}
但它顯示了運行時檢查失敗#2-當我將int k[11]
更改為int k[32]
時,圍繞變量'k'的堆棧已損壞。
數組元素至少為32,為什么?
數組索引從0開始。您將n增加得太早。 顯然,數組大小太小10。 什么公式給出該大小?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.