【问题标题】:Why is my compiler skipping function call?为什么我的编译器跳过函数调用?
【发布时间】:2021-08-06 10:29:05
【问题描述】:
#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 工作之前显示和创建。 print 语句后的函数(即插入和显示函数)不起作用。

【问题讨论】:

  • fflush() 不应以stdin 作为参数调用。所以首先要做的是重构代码,这样你就可以删除所有的fflush(stdin) 调用。
  • 使用调试器并单步调试代码。它会告诉你发生了什么。
  • malloc.h 已经过时了。请改用 stdlib.h。

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


【解决方案1】:

很多问题.....

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

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

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

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

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

【讨论】:

    【解决方案2】:

    如果您尝试追加一个节点,函数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 或另一个函数中完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多