首页 > 解决方案 > 我在链表开头插入数字的代码无法编译

问题描述

这是代码

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
    int data;
    struct node* next;
}node;

node* head;// global variable can be accessed anywhere

void Insert(int x);//function to insert the number in start
void print();//function to print them

int main()
{
    head = NULL;// empty list

    printf("How many numbers?\n");
    int n,i,x;
    scanf("%i", &n);

    for(i = 0; i < n; i++)
    {
        printf("Enter the Number\n");
        scanf("%i", &x);
        Insert(x);
    }
    print();
}

void Insert(int x)
{
    node* temp = malloc(sizeof(node));
    temp->data = x;
    temp->next = head;
    head = temp;
}

void print()
{
    node* temp = head;

    print("List is: ");

    while(temp != NULL)
    {
        printf("%d ",temp->data);
        temp = temp->next;
    }
    printf("\n");
}

所以我尝试在 VS Code 中编译代码,它要求输入多少个数字,然后要求输入数字,输入第一个数字后,程序停止。所以我尝试在 CS50 ide 中编译,这是我得到的错误-

linkedlist1.c:41:1: error: all paths through this function will call itself [-Werror,-Winfinite-recursion]
{
^

第 41 行是函数的第一个大括号void print()

为什么会这样?&我应该如何解决它?

标签: clinked-listcs50

解决方案


打电话

print("List is: ");

函数内部

void print()

unconditionally 是无限递归。

你的意思可能是

printf("List is: ");

printf用调用f,不调用print

为避免这种错误,您应该将不带参数的函数标记为不显式地带参数。这可以通过使用voidas 参数来完成

void print(void)

推荐阅读