Segmentation Fault in a for() loop

Hi, I'm pretty new to programming and I'm sure this is a quick fix. I've just been staring at this code for hours so nothing is popping out at me that would indicate a problem.

All vectors and variables are declared.

1
2
3
4
5
6
7
8
9
10
int radiation;
vector <vector <int> > path;
int totalRad;

for(int q=0;q<path.size();q++){
cout << "Input radiation value for (" << path.at(q).at(0) << "," << path.at(q).at(1) << "): ";
cin >> radiation;
totalRad= totalRad+ radiation;
path.at(q).push_back(radiation);
cout << totalRad << endl;}


The program outputs the last value for "totalRad", but then says "Segmentation Fault." I have no idea where this could be happening!

Let me know if any more code is needed for context. It's almost 200 lines long, so I didn't want to post it here.

Thanks!

Edit: fixed q=0
Last edited on
I expect path.at(q) is throwing a range error. The vector's size is zero, but you're indexing past its size.
closed account (D80DSL3A)
Another problem may lie with line 5: Shouldn't that be int q=0; not int q-0; ? This would leave q uninitialized. If q is negative the test q<path.size() would be met.
+1 fun2code
Well spotted!
The q-0 is a mistake in my copying. It is actually q=0. However I'll look into the initial suggestion!
Topic archived. No new replies allowed.