-1

I've just started DSA recently and this question may seems trivial, but big thanks to those who take it seriously. This is my program:

#include<stdio.h>
#include<stdlib.h>

struct node{
    int data;
    struct node *link;
};

typedef struct node node;
    
void printNodes(node* head) {
    if(head == NULL)
        printf("Linked list is empty");
    node *ptr = head;
    while(ptr != NULL) {
        printf("%d ", ptr->data);
        ptr = ptr->link;
    }
}

int main() {
    node *head = NULL;
    head = malloc(sizeof(node));
    head->data = 3;
    head->link = NULL;

    node *current = NULL;
    current = malloc(sizeof(node));
    current->data = 4;
    current->link = NULL;
    head->link = current;
        
    current = malloc(sizeof(node));
    current->data = 5;
    current->link = NULL;
    head->link->link = current;
    
    printNodes(head);
}

I have the function below to traverse and print the data of nodes in the linked list:

void printNodes(node *head) {
    if(head == NULL)
        printf("Linked list is empty");
    node *ptr = NULL;
    ptr = head;
    while(ptr != NULL){
        printf("%d ", ptr->data);
        ptr = ptr->link;
    }
}

I think the code works just fine if we don't use the node* ptr:

void printNodes(node *head) {
    if(head == NULL)
        printf("Linked list is empty");
    while(head != NULL){
        printf("%d ", head->data);
        head = head->link;
    }
}

Please tell me if my there is any problem in my thought.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    There is no question here. Please: (1) specify what exactly the problem is (2) how that problem can be reproduced -- provide the code that calls this function (3) how you have used a debugger to analyse the problem (4) tag the question with the programming language you are using. – trincot Jun 20 '23 at 15:03

1 Answers1

0

As the pointer head that points to the first node of the list is passed to the function by value that is the function deals with a copy of the value of the pointer head then the function is unable to change the original pointer head declared in main.

In this case the pointer ptr may be removed from the function definition.

Pay attention that as the function does not change the list itself then its parameter should be declared with qualifier const as for example

void printNodes( const node *head )
{
    if ( head == NULL )
    {
        printf("Linked list is empty");
    }
    else
    {
        while ( head != NULL )
        {
            printf("%d ", head->data);
            head = head->link;
        }
    }
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335