The reason is that, in the partial statement
cin >> start >> tmn >> dis[start][tmn]
the evaluation of expressions start
, tmn
, and dis[start][tmn]
are unsequenced with respect to each other, or to the first call of the stream's operator>>()
.
One possible sequencing permits dis[start][tmn]
to be evaluated (to obtain a reference to an array element) before calling the relevant operator>>()
functions that read start
and tmn
. In that case start
and tmn
are uninitialised (since their values have not been read) and accessing their values (necessary to evaluate dis[start][tmn]
) gives undefined behaviour.
The solution (which also helps make the code more readable for humans) is to avoid complex expressions that that rely on (or in your case, incorrectly assume) particular orders of evaluation.
Instead of (blech!)
for (int i = 0; i < e; i++)
cin >> start >> tmn >> dis[start][tmn] >> cost[start][tmn],
dis[tmn][start] = dis[start][tmn], cost[tmn][start] = cost[start][tmn];
(I've broken the statement into two lines) break the input statement into separate statements - which will be sequenced relative to each other - and avoid using the ,
operator to achieve other effects in the same statement.
for (int i = 0; i < e; i++)
{
cin >> start >> tmn;
cin >> dis[start][tmn] >> cost[start][tmn];
dis[tmn][start] = dis[start][tmn];
cost[tmn][start] = cost[start][tmn];
}
It would probably also be a good idea to check that start
and tmn
are valid, before trying to read dis[start][tmn]
and cost[start][tmn]
.
Although you haven't asked about it, the while (cin >> v, v)
probably also does not do what you think it does.