Search code examples
functionloopslinked-listnodestrace

My C code tracing and output is different but I am not sure why?


I am tracing a linked-list C code given by my professor but I am not sure how it is working. The first part confused me the most. I thought the head would be 4 and since temp is 0, head+temp would be 4. However, ptr is 5 and not 4. Can anyone explain what happened? I put the actual outputs in the comments besides the code.

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int info;
    struct node *next;
};
typedef struct node node;
int func1 (node *head)
{
    int temp = 0;
    while (head !=NULL) 
    {
        temp = temp + head -> info;
        head = head->next;
    }
    return(temp);
}
int main() 
{
    node *ptr,*ptr2,*ptr3; //ptr ptr2 ptr3 

    ptr = (node*)malloc(sizeof(node));
    ptr->info = 4;//what is this??
    ptr2 = (node*)malloc(sizeof(node));
    ptr->next = ptr2;
    ptr2->next = NULL;
    ptr->next->info = 1;//5 1 <-actual list //what happened to 4?? 

    printf("ptr2 %d\n",func1(ptr2));//1 
    printf("ptr %d\n",func1(ptr));//5 

    ptr3 = (node*)malloc(sizeof(node));//5 1 _ 
    ptr3->next = ptr;//5 1 _ ? //but there's no space for ptr3->next??

    ptr3->info = 2;//5 1 7 <-actual list
    printf("ptr3 %d\n",func1(ptr3));//7 

    ptr2->info = 8;//12 8 14 <-actual list
    printf("ptr3 %d\n",func1(ptr3));//14 

    ptr->info = 16;//24 8 26 <-actual list
    printf("ptr2 %d\n",func1(ptr));//24     
}

Solution

  • Added comments but it seems to make sense to me?

    ptr = (node*)malloc(sizeof(node));
    ptr->info = 4;//what is this??
    

    // 4 is is the value you are putting into this node

    ptr2 = (node*)malloc(sizeof(node));
    ptr->next = ptr2;
    ptr2->next = NULL;
    

    // ptr is first element in the linked list, ptr2 is now the second

    ptr->next->info = 1;//5 1 <-actual list //what happened to 4?? 
    

    // Assigning value to ptr->next, i.e. ptr2 - 4 is left intact in the first node

    printf("ptr2 %d\n",func1(ptr2));//1 
    

    // 1 makes sense since ptr2 is the last element in the linked list

    printf("ptr %d\n",func1(ptr));//5 
    

    // 5 makes sense since ptr is the first element

    ptr3 = (node*)malloc(sizeof(node));//5 1 _ 
    ptr3->next = ptr;//5 1 _ ? //but there's no space for ptr3->next??
    

    // no space? // ptr3 is now the first element in the linked list

    HTH!