krahets/hello-algo · error

辺インデックスが範囲外であるか、同一です

Error message

辺インデックスが範囲外であるか、同一です

What it means

Japanese localization of the addEdge guard (see error 602). addEdge rejects negative or out-of-range endpoint indices and forbids i == j (self-loops) because this models a simple undirected graph. Logged to stderr; adjMat unchanged.

Source

Thrown at ja/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

  1. Pass 0-based vertex indices, not values.
  2. Insert both vertices first so endpoints are in range.
  3. Forbid i == j at the call site.

Example fix

// before
addEdge(graph, 1, 3);   // values, not indices

// 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

When it happens

Trigger: addEdge(graph, i, j) with i/j < 0, i/j >= graph->size, or i == j — commonly vertex values passed instead of indices, or a self-loop attempt.

Common situations: Value-vs-index confusion; self-loops in a simple-graph model; edges added before endpoints exist.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/dc09d46b284f74aa. Report an issue: GitHub.