I have this code:
#include <iostream>
#include <iomanip>
using namespace std;
main()
{
int i, n, a[n], b[n], c[n];
cout << "Program kreira nizove po matematickoj zavisnosti" << endl;
cout << "Unesite vrednost n =" << endl;
cin >> n;
for (i = 0; i <=n; i++)
{
a[i] = (i+1)*2;
if (i%2==0) b[i] = 2*i;
else b[i] = -2*i;
c[i] = a[i] - b[i];
}
cout << "A" << setw(3) << "B" << setw(3) << "C" << endl;
cout << a[i] << setw(3) << b[i] << setw(3) << c[i] << endl;
}
And it shows me "Process returned -1073741571 (0xC00000FD)" Can't find what is problem. When I try other code, it works. Platform is Win 10.
You are using a non-standard variable-length array (VLA) C++ extension, and you have stack overflow because n
is not initialized before declaring arrays like a[n]
.
If you want to keep using VLA, need to move declaration int a[n], b[n], c[n];
below cin >> n;
. Or use std::vector<int>
instead.
This line:
int i, n, a[n], b[n], c[n];
has two problems:
Variable length arrays are non-standard, and:
n
is uninitialised so a[n]
tries to allocate an array of some indeterminate size on the stack. Which, in your case, is too large and is causing a stack overflow.
So, initialise n
before you use it, and rather than using variable length arrays, use std::vector
.
Achieved to find solution... Here is the final result:
#include <iostream>
#include <iomanip>
using namespace std;
main()
{
int i, n, a[100], b[100], c[100];
cout << "Program kreira nizove po matematickoj zavisnosti" << endl;
cout << "Unesite vrednost n = ";
cin >> n;
cout << "A" << setw(10) << "B" << setw(10) << "C" << endl;
for (i = 0; i <= n; i++)
{
a[i] = (i+1)*2;
if (i%2==0) b[i] = 2*i;
else b[i] = -2*i;
c[i] = a[i] - b[i];
cout << a[i] << setw(10) << b[i] << setw(10) << c[i] << endl;
}
}
I changed value of array to something I'll never use (like 100) and I put cout in for loop, so it can type results one under other. It managed to work perfectly. Thank you for your help!
User contributions licensed under CC BY-SA 3.0