为什么这段代码没有在 vs 代码上运行,而它在 onlinegdb 上运行良好

时间:2021-03-23 13:42:45

标签: c visual-studio-code vscode-settings

它在 vs 代码中提供输入时停止......而它在在线 c 编译器 onlinegdb 上工作。 我应该怎么做才能让它在 vs 代码中也能工作,vs 代码中的所有设置似乎也很好,但不知何故这段代码不起作用

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

1 个答案:

答案 0 :(得分:2)

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

错了。这一行 ls 只分配一个指针,而结构需要一个空间。还转换 malloc() is considered as a bad practice 的结果。

应该是

        newnode= malloc(sizeof(*newnode));

        newnode= malloc(sizeof(struct node));