图邻接矩阵实现中,为何使用`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 hasvertexCountelements, each being abool*(a pointer to boolean values). - Then, the inner loop assigns a new one-dimensional
boolarray (sizevertexCount) to each pointer in that array. Every element in these boolean arrays is initialized tofalse(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 singleboolor a one-dimensional array ofbools. 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":- The first layer:
adjacencyMatrixitself points to an array ofbool*pointers (each representing one row of the matrix). - The second layer: Each
bool*in that array points to a one-dimensional array ofbools (the actual edge values for that row).
- The first layer:
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

