首页 > 解决方案 > Why is this code not running on vs code while it's running fine on onlinegdb

问题描述

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);
    }
}

标签: cvisual-studio-codevscode-settings

解决方案


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

是错的。这一行 ls 仅分配一个指针,而结构需要一个空间。也铸造结果malloc() 被认为是一种不好的做法

它应该是

        newnode= malloc(sizeof(*newnode));

或者

        newnode= malloc(sizeof(struct node));

推荐阅读