c - 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
#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);
}
}
解决方案
newnode= (struct node*)(malloc(sizeof(newnode)));
是错的。这一行 ls 仅分配一个指针,而结构需要一个空间。也铸造结果malloc()
被认为是一种不好的做法。
它应该是
newnode= malloc(sizeof(*newnode));
或者
newnode= malloc(sizeof(struct node));
推荐阅读
- python - 将 C_ulong_Array_40 转换为 python 中的列表或字符串?
- perforce - Perforce:如何查看某些更改是否在特定版本的分支内?
- python - Celery 不再通过 Heroku 连接到 Redis
- python - 如何让警告命令在用户 ID 之后获取所有内容
- python - 没有足够的值在 plt.pcolormesh 中解压
- python - 以有效的方式组合正则表达式 python
- php - 使用中间件后,重定向到 url 显示“此页面不工作”。但是当我删除中间件时,会显示页面
- python - 将整数转换为字符串过程(“幕后”)
- sql - 用随机数据填充表
- pine-script - 在 RSI 上绘制背离