You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图邻接矩阵实现中,为何使用`bool** adjacencyMatrix;`做动态分配?

Hey Marcus, let's break down your questions about this adjacency matrix code clearly!

What Does adjacencyMatrix Point To?

After running the constructor code, here's the exact structure adjacencyMatrix refers to:

  • First, adjacencyMatrix = new bool*[vertexCount]; creates a dynamically allocated array of pointers. This array has vertexCount elements, each being a bool* (a pointer to boolean values).
  • Then, the inner loop assigns a new one-dimensional bool array (size vertexCount) to each pointer in that array. Every element in these boolean arrays is initialized to false (meaning no edges exist between any vertices at the start).

In short: adjacencyMatrix is a pointer that points to a list of pointers, where each nested pointer points to a row of your adjacency matrix. The whole setup acts like a vertexCount × vertexCount 2D matrix, where adjacencyMatrix[i][j] tells you if there's an edge connecting vertex i and vertex j.

Why Do We Use bool** adjacencyMatrix;?

Let's unpack the pointer hierarchy here:

  • A bool* can only point to a single bool or a one-dimensional array of bools. But we need a 2D matrix structure for the adjacency list.
  • A bool** is a pointer to an array of pointers—this is exactly what we need for our dynamic 2D matrix, which is built as an "array of arrays":
    1. The first layer: adjacencyMatrix itself points to an array of bool* pointers (each representing one row of the matrix).
    2. The second layer: Each bool* in that array points to a one-dimensional array of bools (the actual edge values for that row).

If we tried using just bool*, we could only represent a 1D array—there'd be no way to reference the separate rows of our matrix. The bool** type lets us correctly handle this two-layered dynamic allocation.

Think of it like a bookshelf: bool** is the pointer to the shelf itself, each bool* is a pointer to a shelf row, and each bool is a book in that row. You need the double pointer to first locate the shelf, then access each individual row.


内容的提问来源于stack exchange,提问作者Marcus Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:23:09