[英]I am Working with Doubly Linked Lists in C and I am Using Turbo C++ but The Compiler is Taking Two Additional Nodes without Adding
I am Working With Doubly Linked List & Implementing Them using C I am using Turbo C++ as my Compiler But it's Taking Two Constant Additional Nodes Every Time without Writing Code for It The Same Code is Running in VS Code But I Should Run it In Turbo C++ I tried Changing Systems, but it didn't Work I am Working With Doubly Linked List & Implementing Them using C I am using Turbo C++ as my Compiler But it's Taking Two Constant Additional Nodes Every Time without Writing Code for It The Same Code is Running in VS Code But I Should Run it In Turbo C++我尝试更改系统,但它没有工作
'''
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct Node
{
struct Node *prev;
int data;
struct Node *next;
} * head = NULL, *temp = NULL;
void insatbeg()
{
int item;
struct Node *ptr = NULL;
printf("\nEnter Item: ");
scanf("%d", &item);
ptr = (struct Node *)malloc(sizeof(struct Node *));
if (ptr == NULL)
printf("\nOverflow Occured");
else if (head == NULL)
{
ptr->data = item;
ptr->next = ptr->prev = NULL;
head = ptr;
}
else
{
ptr->prev = NULL;
ptr->data = item;
ptr->next = head;
head->next->prev = ptr;
head = ptr;
}
}
void display()
{
if (head == NULL)
printf("\nList is Empty");
else
{
temp = head;
while (temp != NULL)
{
printf("%d\t", temp->data);
temp = temp->next;
}
}
}
int main()
{
int loopvar = 1, switchvar;
clrscr();
code:
while (loopvar == 1)
{
printf("\nEnter 1 to Insert at First");
printf("\nEnter 2 to Disply");
printf("\nEnter: ");
scanf("%d", &switchvar);
switch (switchvar)
{
case 1:
insatbeg();
break;
case 2:
display();
break;
default:
printf("\nEnter Properly: ");
goto code;
break;
}
printf("\nDo You Want to Continue: ");
scanf("%d", &loopvar);
}
getch();
}
'''
Should I consider it as Compiler Fault我是否应该将其视为编译器错误
This memory allocation本memory配置
ptr = (struct Node *)malloc(sizeof(struct Node *));
is invalid.是无效的。 You allocated a memory for the pointer type
struct Node *
while you need to allocate memory for an object of the type struct Node
.您为指针类型
struct Node *
分配了 memory 而您需要为类型struct Node
的 object 分配 memory。 So write所以写
ptr = (struct Node *)malloc(sizeof(struct Node));
Also in this code snippet同样在此代码段中
else
{
ptr->prev = NULL;
ptr->data = item;
ptr->next = head;
head = ptr;
}
you forgot to set the data member prev
of the head node.您忘记设置头节点的数据成员
prev
。 Write写
else
{
ptr->prev = NULL;
ptr->data = item;
ptr->next = head;
head->prev = ptr;
head = ptr;
}
Pay attention to that the pointer temp1
is not used in your program.请注意,您的程序中没有使用指针
temp1
。
If the code does not work as expected using the compiler Turbo C++ then try to initialize the pointer to the head node explicitly如果使用编译器 Turbo C++ 代码无法按预期工作,则尝试显式初始化指向头节点的指针
struct Node
{
struct Node *prev;
int data;
struct Node *next;
} *head = NULL, *temp, *temp1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.