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

Why is my compiler skipping function call?

#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 工作之前显示和创建。 打印语句后的功能(即插入和显示功能)不起作用。

很多问题......

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

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

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

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

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

如果您尝试再追加一个节点,函数 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 中完成。它应该在一个函数中完成。

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