【问题标题】:My code for inserting numbers to the start of linked list doesn't compile [closed]我在链表开头插入数字的代码无法编译[关闭]
【发布时间】:2021-09-08 20:39:08
【问题描述】:

这是代码

#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() 的第一个大括号

为什么会这样?以及我应该如何解决?

【问题讨论】:

  • 我猜你有print("List is: "); 错了。这将触发无限递归。应该是printf("List is: "); 不?
  • 一个技巧:使用函数原型。

标签: c linked-list cs50


【解决方案1】:

打电话

print("List is: ");

函数内部

void print()

无条件是无限递归。

你的意思可能是

printf("List is: ");

(用f 打电话给printf,而不是print)

为避免此类错误,您应该将不带参数的函数标记为不显式带参数。这可以通过使用void 作为参数来完成,例如

void print(void)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多