pointer question

I came across a strange piece of code and I was wondering if this is correct way to do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Graph
{
	int V;    // No. of vertices
	vector<int> *adj;    // Pointer to an array containing adjacency lists
..
..
..


void Graph::addEdge(int v, int w)
{
	adj[v].push_back(w); // Add w to v’s list.
}


The structure should have been vector< vector <int> > adj; .

I am really curious to know how vector<int> *adj works here.
I verified it works by printing the output and here is what I get

Adding Edge 0,1
Printing out vector 0 values
1
Adding Edge 0,2
Printing out vector 0 values
1 2
Adding Edge 1,2
Printing out vector 1 values
2
Adding Edge 2,0
Printing out vector 2 values
0
Adding Edge 2,3
Printing out vector 2 values
0 3
Can someone please look into this and help my understanding?
[brackets] can be used on pointers. When done so, C++ treats the pointer as if it points to the first element in an array:

1
2
3
4
5
6
int array[10];  // <- an array
int* ptr;  // <- a pointer

ptr = array; // <- pointer points to the first element in the array

ptr[0] = 5; // <- legal.  Same as doing: "array[0] = 5;" 


Here, since 'adj' is a pointer to a vector, the language will allow you to use brackets the same way:

1
2
3
4
5
vector<int> foo[5]; // <- an array of vectors

adj = foo; // <- adj points to first element in 'foo' array

adj[0].push_back(5);  // <- legal.  Same as: "foo[0].push_back(5);" 


Note that this is legal syntax and therefore will always compile. However if you do this (or anything dealing with raw pointers), you must always be sure that your pointer actually points to something or else results can be catastrophic:

1
2
3
int* ptr;  // <- an ininitialized pointer (doesn't point to anything)

ptr[5] = 9;  // <- legal syntax, will compile okay, but may cause program to crash 

Last edited on
Topic archived. No new replies allowed.