jay
jay

Reputation: 99

How can I print input data?

As a practice for final exam, I am practicing a linked list. But now I am stuck at printing input data on my code. I made this linked list and want to print input data. But my code does not print anything.

What's wrong with my code?

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

typedef struct Node{
    int a,b ;
    struct Node* next;
}NODE;

void makenode()
{
    int a;
    int b;

    printf("enter the name : ");
    scanf("%d",&a);
    printf("enter the sur name : ");
    scanf("%d",&b);

    NODE* node1=malloc(sizeof(NODE));

    node1->a=a;
    node1->b=b;
    node1->next=NULL;

    return node1;

}

void printList()
{
    NODE *ptr=NULL;
    while(ptr!=NULL){
        printf("%d", ptr->a);
        printf("%d", ptr->b);
        ptr = ptr->next;
    }
}

int main()
{
    NODE *head = malloc(sizeof(NODE));
    head->next=NULL;
    makenode();
    printList();
    return 0;
}

Upvotes: 1

Views: 93

Answers (1)

anastaciu
anastaciu

Reputation: 23792

makenode() return type is void, it should be NODE*.

printList() does not fech the list so it can't know what to print, moreover ptr is NULL so it never enters the print loop.

Fixed code with comments:

Live demo

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

typedef struct Node {
    int a, b;
    struct Node *next;
} NODE;

NODE* makenode() { //return type NODE*

    NODE *node1 = malloc(sizeof(*node1));

    printf("enter the name : ");
    scanf("%d", &node1->a);
    printf("enter the sur name : ");
    scanf("%d", &node1->b);
    node1->next = NULL;

    return node1;
}

void printList(const NODE *ptr) { //pass NODE* ptr as an argument

    int i = 1;
    while (ptr != NULL) {
        printf("Node %d\n", i++);
        printf("a: %d\n", ptr->a);
        printf("b: %d\n", ptr->b);
        ptr = ptr->next;
    }
}
int main() {

    //make first node
    NODE *head = makenode(); //assing node

    // add one more node
    NODE* node = makenode();
    head->next = node; //chain second node

    printList(head); //print nodes

    return EXIT_SUCCESS;
}

On another note:

It's kind of strange that the names are int and not strings.

You could do:

Live demo

typedef struct Node {
    char name[100]; //names as strings
    char surname[100];
    struct Node *next;
} NODE;

NODE* makenode() { //return type NODE*

    NODE *node1 = malloc(sizeof(*node1));

    printf("enter the name : ");
    scanf(" %99[^\n]", node1->name);
    printf("enter the sur name : ");
    scanf(" %99[^\n]", node1->surname);
    node1->next = NULL;

    return node1;
}

void printList(const NODE *ptr) { //pass NODE* ptr as an argument

    int i = 1;
    while (ptr != NULL) {
        printf("Node %d\n", i++);
        printf("Name: %s\n", ptr->name);
        printf("Surname: %s\n", ptr->surname);
        ptr = ptr->next;
    }
}

//...
//main is the same

Upvotes: 1

Related Questions