Possible Duplicate:
Matrix Arithmetic using Vectors in C++ causing segmentation faults
I created this simple code in C++ to assign some values to a dynamic matrix:
unsigned N = 1000;
vector<vector<double> > Matrix;
for (unsigned i=0; i<(N-1); ++i) {
for (unsigned j=0; j<(N-1); ++j) {
if ((i>(N/4-1) && i<(3*N/4-1)) || (j>(N/4-1) && j<(3*N/4-1)))
Matrix[i][j] = 1;
else if (i==0 || i==(N-1) || j==0 || j==(N-1))
Matrix[i][j] = 0;
}
}
The compiler does not return any problem, but when I try to run the program, it returns: Segmentation Fault. Where is my mistake?
Thank you for your attention.
You are just creating two empty vectors, and using the
operator[]is undefined behaviour. They are like arrays of size 0, if such a thing was possible.You have to create the vectors with a capacity, and each element will be default-initialised to 0:
The first argument is the size of the outer
vector, and the second is the value to copy into each element, which is itself a vector ofNdoubles.