In C programming, how can we initialize this int *goo
, where goo is a list of edges for a graph?

- 74,820
- 37
- 200
- 327
-
3`int *goo` is a (pointer to) a flat array of integers. How do you intend to store the edges of a graph in something like this? – thkala Jan 28 '11 at 18:41
1 Answers
A one-dimensional integer array cannot in general be used to store a graph intuitively, i.e. without some sort of mapping code.
There are at least two common ways to mathematically represent a graph in a matrix/array. Assuming N
numbered vertices and M
edges:
An
N x N
adjacency matrix. This is a two-dimensional array, where each vertex has its own line.An
M-sized
adjacency list. This essentially boils down to a list of the edges and can be implemented as aM x 2
array, where each edge has its own line.
Both of these representations are intuitively two-dimensional K x L
arrays. You can use a one-dimensional array by using extra code to place the data in a (K * L) x 1
one-dimensional array A
. E.g. to get the (i, j)
element of the original K x L
array:
e = A[i * L + j];
Then you can simply allocate the array dynamically:
int *A = (int *)malloc(K * L * sizeof(int));
(Before anyone whines about the explicit cast, it is needed in C++ and that's a good enough reason for me)

- 84,049
- 23
- 157
- 201