Reputation: 1633
I'm trying to represent a graph using adjacency list but I'm having trouble with pointers.
typedef struct vertex{
int num;
struct vertex *next;
} Vertex;
Vertex *adj[10];
void build(){
Vertex *v=NULL;
Vertex *t=NULL;
v = malloc(1*sizeof(*v));
v->num = 1;
adj[0] = v; //NODE with value 1
t = v;
v = malloc(1*sizeof(*v));
v->num = 1;
t->next = v; // ANOTHER NODE but it should be the SAME NODE with the above one
t = v;
//v = malloc(1*sizeof(*v));
//v->num = 1;
//t->next = adj[0]; // causes infinite loop...
//t = v;
v = malloc(1*sizeof(*v));
v->num = 2;
t->next = v;
t = v;
}
What I'm trying to build is actually simple. 1 --> 1,2 . But the code I wrote didn't work. What could be the problem?
EDITED: Ok, I corrected the NULL's. The expected output is 1 -->> 1,2 . A graph that has 2 nodes 1 points to itself and to the next node with value 2. My problem is when I create the graph after getting the list 1 --> 1,2; it looks like I have 3 different nodes. I mean later when I change value of node with 1 to 3, I get 3 --> 1,2 but since I only should have 2 nodes, desired output should have been 3 --> 3,2 after I made that change.
Upvotes: 0
Views: 221
Reputation: 206526
t = NULL;
v = malloc(1*sizeof(*v));
v->num = 2;
t->next = v; //This is basically dereferencing a NULL pointer
You are dereferencing t
after setting it to NULL
causing an Undefined Behavior.
Also, You should tell us:
What is the expected output?
What is the output that you are getting?
Without that information, it is difficult to tell what you are doing wrong except pointing out to you the obvious usage errors.
Upvotes: 2
Reputation: 36433
You are trashing t
in several places. Specifically with the t = v;
, you don't have the original value anywhere else.
Upvotes: 1