I've started using C++ just this week. I've been using matlab for a few years. I want to do an N size array and I get this error with visual studio. Anyone can help me with that?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
double limit = 8;
int step = 100;
double w = limit / step;
double x[step];
x[0] = 0;
for (int i = 1; i < step; i++) {
x[i] = x[i - 1] + w;
}
system("pause>0");
}
error C2131: expression did not evaluate to a constant
message : failure was caused by a read of a variable outside its lifetime
message : see usage of 'step'
Can someone explain me how I can allocate more memory to avoid stack overflow errors? I need to deal with big array but I always get stack overflow error. again using visual studio.
your vector is empty and there you are accessing it. you can use push back or preallocate to give it some space.
std:: vector<double> x(step,0); //size, value
for (int i = 1; i < x.size(); i++)
If you know the size of the array at compile time, then you can use std::array or even just a c-style array. If you get stack overflow error, then mark the array definition as static - or define as a global (before main).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main() {
constint step = 100;
constdouble limit = 8;
constdouble w = limit / step;
staticdouble x[step];
x[0] = 0;
for (int i = 1; i < step; i++) {
x[i] = x[i - 1] + w;
}
}
Just for info. Note that in c/c++ int division gives an integer! So 5 / 7 gives 0 - even if the result is assigned to a type double! If you want a non-integer result, then at least one of the divisor and dividend needs to be float/double.
I missed that note before. Its fair to say that matlab and C++ approach how to code from polar opposite positions. Matlab was designed to be easy to use by non-coders, math people that just want to express a problem quickly and easily. C++ was designed for professional coders who need to know every detail, matlab HIDES a ton of details (type, dimensions, hidden copying, more (modern c++ is bad in a few places about the hidden loops and hidden copies as well) ). Matlab seems to have a loose C syntax root, so at times things will feel familiar, but even so be prepared for some shocks along the way.