Adjacency list, array of pointers

Hi guys, can someone explain me why to use a double pointer in the class graph?
I really don't understand this line : this->array = new AdjList*[Algorithme::nb]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 

#include <iostream>
#include <fstream>
#include <cstring> 
#include <string> 
using namespace std;



class AdjListNode
			{
		public:
				AdjListNode (char dest [6], float weight); // constructor
				char dest [6];
				float weight;
			    class AdjListNode *next;
			};


			
class AdjList
			{
			public:

			 AdjListNode *head; 
			};

			
			
class Graph
			{
			public:
				Graph (); 
				int V;
			    AdjList **array; 
			};

Graph:: Graph()

{



this -> V = Algorithme::nb ;
    
    this->array = new AdjList*[Algorithme::nb] ; 


    
    for (int i = 0; i < Algorithme::nb ; ++i){
    	this->array[i]= new AdjList(); 
        this->array[i]->head = NULL;

    }

}



Last edited on
Did a monkey indent your code?
OP's code, reformatted:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

class AdjListNode {
 public:
  AdjListNode(char dest[6], float weight);  // constructor
  char dest[6];
  float weight;
  class AdjListNode* next;
};

class AdjList {
 public:
  AdjListNode* head;
};

class Graph {
 public:
  Graph();
  int V;
  AdjList** array;
};

Graph::Graph() {
  this->V = Algorithme::nb;

  this->array = new AdjList*[Algorithme::nb];

  for (int i = 0; i < Algorithme::nb; ++i) {
    this->array[i] = new AdjList();
    this->array[i]->head = NULL;
  }
}


The double pointer is used because that variable is meant to point to an array of pointers. The line you were having trouble with (this->array = new AdjList*[Algorithme::nb];) allocates an array of AdjList* pointers of length Algorithme::nb.

Side note, I don't see any a destructor declared in Graph. Please remember to free up that array (AND every AdjList its pointers point to).

-Albatross
Topic archived. No new replies allowed.