0

It stops while giving input in vs code.... while it works on online c compiler, onlinegdb. What should I do so it works in vs code too, all the settings in vs code also seem to be fine but somehow this code is not working

enter image description here

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    int exp;
    struct node *next;
};

int main()
{
    int n,i=0;
    struct node *head,*newnode,*temp;
    head=0;
    printf("Enter number of elements:");
    scanf("%d",&n);
    while(i<n)
    {
        newnode= (struct node*)(malloc(sizeof(newnode)));
        printf("Enter data:");
        scanf("%d",&newnode->data);
        printf("Enter Power:");
        scanf("%d",&newnode->exp);
        newnode -> next=0;
        if(head==0)
        {
            head=temp=newnode;
        }
        else
        {
            temp->next=newnode;
            temp=newnode;
        }
        temp->next=head;
        i++;
    }

    struct node *temp1;
    if(head==0)
    {
        printf("Empty list");
    }
    else
    {
        temp1=head;
        while(temp1->next !=head)
        {
            printf("%d(x)^%d",temp1->data,temp1->exp);
            temp1=temp1->next;
            if((temp1->data)<0)
            {
                printf(" ");
            }
            else
            {
                printf(" + ");
            }
        }
         printf("%d(x)^%d",temp1->data,temp1->exp);
    }
}
rioV8
  • 24,506
  • 3
  • 32
  • 49
reaper
  • 5
  • 2
  • VS code is just an editor, btw. If its compiling and running code for you, you probably have some extensions installed. For future questions, please add your compiler name and version for such questions. – TSG Mar 23 '21 at 14:13
  • do you use a terminal that does not allow copy paste of the text – rioV8 Mar 23 '21 at 14:27
  • I would change `while(temp1->next !=head)`to `while(temp1 != NULL)`, and move `temp1 = temp1->next;` to the bottom of the loop. Moreover I would replace the 11-line tangle beginning with `newnode -> next=0;` with just two lines: `newnode->next = head; head = newnode;` – Weather Vane Mar 23 '21 at 15:02

1 Answers1

2
        newnode= (struct node*)(malloc(sizeof(newnode)));

is wrong. This line ls allocating only for one pointer while a space for the structure is required. Also casting the result of malloc() is considered as a bad practice.

It should be

        newnode= malloc(sizeof(*newnode));

or

        newnode= malloc(sizeof(struct node));
MikeCAT
  • 73,922
  • 11
  • 45
  • 70