为什么我的编译器跳过函数调用?

时间:2021-05-17 06:33:59

标签: c linked-list dynamic-memory-allocation singly-linked-list function-definition

#include<stdio.h>
#include<malloc.h>
struct node
{
    int data;
    struct node*next;
};
struct node*start;
void create(struct node*ptr)
{
    char ch;
    do
    {
     printf("Enter the data of node\n");
     scanf("%d",&ptr->data);
     fflush(stdin);
     printf("Do you wish to continue?(y/n)\n");
     ch=getchar();
     if(ch=='y')
     {
         ptr=ptr->next;
     }
     else
        ptr->next=NULL;
    }while(ch=='y');
}
void insert(struct node*ptr)
{
    struct node*p;
    p=(struct node*)malloc(sizeof(struct node));
    printf("Enter the value of data for node1\n");
    scanf("%d",&p->data);
    fflush(stdin);
    p->next=ptr;
    ptr=p;
}
void display(struct node*ptr)
{
    printf("Your Linked list is\n");
    while(ptr!=NULL)
    {
        printf("%d ",ptr->data);
        ptr=ptr->next;
    }
    printf("\n");
}
int main()
{
    printf("Hello and welcome to Linked List program\n");
    start=(struct node*)malloc(sizeof(struct node));
    create(start);
    display(start);
    printf("Let us now add a node to your linked list\n");
    insert(start);
    display(start);
    return 0;
}

我的编译器正在跳过函数调用插入和显示。我已经检查了它们对我来说正确的所有功能的逻辑。此外,在 printf 工作之前显示和创建。 打印语句后的功能(即插入和显示功能)不起作用。

2 个答案:

答案 0 :(得分:1)

很多问题.....

create 中,您传递了一个未正确初始化的指针。因此 ptr= ptr->next 使 ptr 成为无效值。在 main 你应该有 start->ptr= 0;

当您只传递一个元素并且不在 create 中分配新元素时,在 create 中使用循环有什么用?

由于第一次观察,display 将尝试获取无效的 ptr->data 并可能中止程序。

insert 中,ptr=p; 不会将更改后的 ptr 传递给调用者,因为参数是本地副本(按值调用)。您必须传递一个双指针,或者使其成为返回值。

如前所述,请使用调试器来了解有关正在发生的事情的更多信息。

答案 1 :(得分:1)

函数 create 可以调用未定义的行为,如果您将尝试追加一个节点,因为在这种情况下在此语句之后

ptr=ptr->next;

指针 ptr 的值不确定。

至少你应该写

 if(ch=='y')
 {
     ptr->next = malloc( sizeof( struct node ) );
     ptr = ptr->next;
 }

虽然你还需要检查内存分配是否成功。

函数insert不改变本语句中的原始指针start

ptr=p;

因为该函数处理原始指针start的值的副本。相反,它更改了局部变量 ptr

函数至少应该写成这样

struct node * insert(struct node*ptr)
{
    struct node*p;
    p=(struct node*)malloc(sizeof(struct node));
    printf("Enter the value of data for node1\n");
    scanf("%d",&p->data);
    fflush(stdin);
    p->next=ptr;
    return p;
}

并称为喜欢

start = insert( start );

尽管该函数不会检查内存是否分配成功。

请注意,将指针 start 声明为全局变量是一个坏主意。

例如,第一个节点的内存分配不应该在主节点中完成。它应该在一个函数中完成。

函数应该做一件事,例如分配一个节点并将其插入列表中。任何要求用户输入值的提示都应该在 main 或另一个函数中完成。

相关问题