#### Creating a dynamic adjacency list for a graph, memory violations

I have to to create a dynamic adjacency list graph based off of a 2D array(40×20) of 0’s and 1’s. The graph will have and egde, if two elements of the array that are exactly 1 distance apart (up, down, left or right only, no diagonals) are both 1’s, which would look like that: (Each vertex has an unique number equal to: (ROW)*(MAX_COLUMNS) + (COLUMN))

``````  0 1 2 3 4
0 0 0 1 1 1
1 1 1 1 0 1
2 1(1)0 1 1
3 0 1 0 1 0
4 1 1 0 1 0

Adjacencylist[(2*5)+1] = {6 , 10 , 16}
``````

Etc.
So far I’ve managed to creat a list for only one of the neighbours of a given vertex, but I’ve got no idea how to add the next neighbour to the neighbour before, nor do I know how to make it work on the edges of the graph(When there is only 2 or 3 neighbours) Here’s the full code: https://ideone.com/r2JRrf , and below is just the part that is problematic to me.

``````struct Wierzcholek {
Wierzcholek* next;
int wartosc;
}
Wierzcholek* p;
Wierzcholek** TablicaList = new Wierzcholek * [LiczbaWierzcholkow];

for (int i = 0; i < LiczbaWierzcholkow; i++)
TablicaList[i] = nullptr;

for (int i = 1; i < 40-1; i++)
for (int j = 1; j < 20-1; j++)
{
if (MacierzGrafu[i][j] == 0) continue;
else
{
if (MacierzGrafu[i - 1][j] == 1)
{
p = new Wierzcholek;
p->wartosc = (((i-1) * 20) + j);
p->next = TablicaList[(i * 20) + j];
TablicaList[(i * 20) + j] = p;
}
/* Here are the algorithms for creating up,down and right neighbours,
// however I'm unable to make them all work together
if (MacierzGrafu[i][j - 1] == 1)
{
p = new Wierzcholek;
p->wartosc = ((i * 20) + j - 1);
p->next = TablicaList[(i * 20) + j];
TablicaList[(i * 20) + j] = p;
}
if (MacierzGrafu[i + 1][j] == 1)
{
p = new Wierzcholek;
p->wartosc = (((i+1) * 20) + j);
p->next = TablicaList[(i * 20) + j];
TablicaList[(i * 20) + j] = p;
}
if (MacierzGrafu[i - 1][j - 1] == 1)
{
p = new Wierzcholek;
p->wartosc = ((i * 20) + j + 1);
p->next = TablicaList[(i * 20) + j];
TablicaList[(i * 20) + j] = p;
}
/*
``````

How should i steer the pointers to make the graph stable(and usable for DFS)?
On a sidenote, how do i give the function a formal parameter that is `Wierzcholek** Vertex`. Any help is greatly appreciated, as I’m fairly new to programming and only really beginning to understand the beautiful complexity of pointers and dynamically allocated memory.

Source: Windows Questions C++