meany
meany

Reputation: 25

C using while loop with linked list

I have come to a problem where I try to use while loop on linked list. I have two linked lists, namely temp and graph. I am using a while loop to do tasks while(temp != NULL). To move on in each of the loop, I am assigning temp = temp->link. However, this code does not compile. I realize that recursive function could be a solution, but the function is actually way more complicated that I don't think recursive would be such a good idea. By the way, graph is already a built linked list. Thanks in advance!

P.S. It is part of homework.

temp = graph->link;
while(temp!=NULL){
    if(stack->link == NULL){
        stack->link = (node_pointer)malloc(sizeof(graph));
        stack->link->weight = temp->weight;
        stack->link->vertex = temp->vertex;
    }
    temp = temp->link; //Here is the problem.
}

edit:

stack and graph are both arrays of linked list:

typedef struct node *node_pointer;

struct node{
    int vertex;
    int weight;
    int visited;
    struct node *link;
};
node_pointer graph[50];
node_pointer stack[50];
node_pointer temp;

Upvotes: 0

Views: 3030

Answers (1)

Aniket Inge
Aniket Inge

Reputation: 25725

0xC00000005 is not a compile time error. This error usually happens when you access a memory location that you're not allowed to, even if its pointing to NULL. Its a runtime error. Check to see if temp is not NULL and is also malloced properly. Is it? Also check all other variables. Use a debugger, run it through valgrind. It will help you learn the language and debugging techniques properly. Especially CompileTime and RuntimeErrors ;-).

Also explicitly make link as NULL when creating a new node. Pointer variables usually contain a JUNK value without initialization. I am assuming you're not setting link to NULL and accessing a JUNK memory location. Garbage in Garbage out. Your logic of IF TEMP(WHICH IS SET TO LINK) IS NOT EQUAL TO NULL fails if LINK is not null but is junk.

Upvotes: 1

Related Questions