开发者

Segmentation fault while trying to print size of a vector inside a structure

This piece of code gives me an error

struct state{
    int time_taken;
    vector<int>time_live;
    string loc_name;
    vector<int>loc;
};


for(int u=0;u<(A[start].loc.size());u++)
{
  l=A[start].loc[1];
  if(A[l].time_taken < min_time)
  { 
    m开发者_如何学Goin_time=A[l].time_taken;
    finish = l;
  }
}

This gives a segmentational fault .


Firstly, if A[start] is out of range then you may get a problem, which may or may not be a seg fault, depending on what A is.

Secondly, in the loop you have A[start].loc[1], which will be out of range if A[start].loc is empty. Did you mean loc[u]?


As from the above code.

before for loop make sure

start < A.size();

Inside for loop

l = A[start].loc[u];  // instead of 1

and before

if(A[l].time_taken < min_time) 
check
if (l < A.size())


I like Anthony Williams's first point, but my guess is that A[l] is out of range.


Perhaps you could try to access A by using A.at(start) if this is out of range it will now throw an exception as opposed to segfaulting

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜