Error run-time check failure #2 Stack around the variable 'N' was corrupted
The program works, but in the end it gives this error:
Run-Time Check Failure #2 - Stack around the variable 'N' was corrupted.
How to solve it and what is the error?
//Определить, является ли шестизначное число "счастливым"
#include "pch.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
setlocale(LC_ALL, "rus");
int N[6]; // шестизначное число
for (int i = 1; i < 7; i++)
{
cout << "Введите " << i << " цифру шестизначного числа\n";
cin >> N[i];
if (N[i] < 0 || N[i] > 9 || N[1] == 0 ) {
cout << "Ошибка!\n";
return 1;
}
}
system("cls");
if (N[1] + N[2] + N[3] == N[4] + N[5] + N[6]) {
cout << "\nВаше число ";
for (int i = 1; i < 7; i++)
{
cout << N[i];
}
cout << " является счастливым!\n\n";
}
else if (N[1] + N[2] + N[3] != N[4] + N[5] + N[6]) {
cout << "\nВаше число ";
for (int i = 1; i < 7; i++)
{
cout << N[i];
}
cout << " не является счастливым :(\n\n";
}
system("pause");
return 0;
}
0
1 answers
int N[6]; // шестизначное число
for (int i = 1; i < 7; i++)
In C++, the numbering of array elements starts from zero, i.e. here
int N[6];
An array with elements is defined N[0]
,N[1]
,N[2]
,N[3]
,N[4]
,N[5]
.
You are trying to work with the N[6]
element, which spoils the whole impression of the program :) along with memory corruption...
2
Author: Harry, 2018-10-20 06:15:43