0

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.

thetux4
  • 1,583
  • 10
  • 25
  • 38
  • You are setting t to NULL after setting t to v. – wildplasser Dec 14 '11 at 11:56
  • you should not completely change the basis of the question. Accept an answer and submit another follow-up question instead. Add complete (though not more than necessary) code then. – moooeeeep Dec 14 '11 at 12:36
  • Then they could complain about possible duplicates:( – thetux4 Dec 14 '11 at 12:38
  • 1
    You have another problem now, then you had before. That's worth setting up another question. At least in my opinion. Be specific in your questions, and try to approach the number of problems per question to one... – moooeeeep Dec 14 '11 at 12:44

2 Answers2

2
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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

You are trashing t in several places. Specifically with the t = v;, you don't have the original value anywhere else.

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151