krahets/hello-algo · error
邊索引越界或相等
Error message
邊索引越界或相等
What it means
Traditional-Chinese localization of the addEdge guard (see error 602). addEdge forbids negative/out-of-range endpoints and self-loops (i == j) because this is a simple undirected graph. Logged to stderr; adjMat unchanged.
Source
Thrown at zh-hant/codes/c/chapter_graph/graph_adjacency_matrix.c:80
for (int i = index; i < graph->size - 1; i++) {
for (int j = 0; j < graph->size; j++) {
graph->adjMat[i][j] = graph->adjMat[i + 1][j];
}
}
// 在鄰接矩陣中刪除索引 index 的列
for (int i = 0; i < graph->size; i++) {
for (int j = index; j < graph->size - 1; j++) {
graph->adjMat[i][j] = graph->adjMat[i][j + 1];
}
}
graph->size--;
}
/* 新增邊 */
// 參數 i, j 對應 vertices 元素索引
void addEdge(GraphAdjMat *graph, int i, int j) {
if (i < 0 || j < 0 || i >= graph->size || j >= graph->size || i == j) {
fprintf(stderr, "邊索引越界或相等\n");
return;
}
graph->adjMat[i][j] = 1;
graph->adjMat[j][i] = 1;
}
/* 刪除邊 */
// 參數 i, j 對應 vertices 元素索引
void removeEdge(GraphAdjMat *graph, int i, int j) {
if (i < 0 || j < 0 || i >= graph->size || j >= graph->size || i == j) {
fprintf(stderr, "邊索引越界或相等\n");
return;
}
graph->adjMat[i][j] = 0;
graph->adjMat[j][i] = 0;
}
/* 列印鄰接矩陣 */View on GitHub (pinned to 69932aed18)
Solutions
- Pass indices, not values.
- Insert both vertices first.
- Forbid i == j at the call site.
Example fix
// before addEdge(graph, 1, 3); // after int i = indexOf(graph, 1), j = indexOf(graph, 3); if (i >= 0 && j >= 0 && i != j) addEdge(graph, i, j);
Defensive patterns
Strategy: validation
Validate before calling
static inline int graphValidEdge(const GraphAdjMat *g, int i, int j) {
return g != NULL && i >= 0 && j >= 0
&& i < g->size && j < g->size && i != j;
}
if (graphValidEdge(graph, i, j)) addEdge(graph, i, j); Prevention
- Pass indices, not values; name variables to make this clear.
- Insert both endpoints before adding the edge.
- Reject i == j at the call site for this simple-undirected model.
When it happens
Trigger: addEdge(graph, i, j) with i/j out of range or equal — typically vertex values mistaken for indices, or a self-loop.
Common situations: Value-vs-index confusion; self-loops; edges created before endpoints are inserted.
Related errors
- Edge index out of bounds or equal
- 辺インデックスが範囲外であるか、同一です
- индексы ребра выходят за границы или совпадают
- 頂點索引越界
- 边索引越界或相等
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/c30b230d9751d348.
Report an issue: GitHub.