【问题标题】:warning: implicit declaration of function in linkedlist警告:链表中函数的隐式声明
【发布时间】:2017-06-12 04:49:24
【问题描述】:
#include<stdio.h>
#include<stdlib.h>

struct node {
    int data;
    int key;
    struct node *next,*ptr;
};
struct node *head = NULL;
void input(){
    ptr=(struct node *)malloc(sizeof(struct node));
    for(int i=0;i<5;i++){
        printf("enter the elements");
        scanf("%d",&ptr->data);
        ptr->key=i;
        ptr=ptr->next;
    }

    void display(){
        ptr=head;
        while(ptr!=NULL){
            printf("the linkedlist is --\n");
            printf("%d",ptr->data);
            ptr=ptr->next;
        }
    }

}

void main(){
    input();
    display(); 
}

这给出了两个错误-

  1. 错误:“ptr”未声明
  2. 警告:函数“display”的隐式声明

我已经声明了 ptr ,那为什么会出现这个错误呢? 那么显示功能呢?我的代码逻辑在链表中输入元素并显示它们是否正确?

【问题讨论】:

  • 我对您的代码进行了格式化,因此不正确的缩进有望像大拇指一样突出。无论如何,唯一的ptrstruct node成员,所以所有ptr = ... 都是错误的。如果你没有,get a good book on C.

标签: c linked-list


【解决方案1】:

未声明的第一个错误 ptr 是因为您已将其声明为结构的一部分。所以你不能直接访问结构成员。您需要创建一个结构变量来访问它。见http://www.c4learn.com/c-programming/c-accessing-structure-members/。 来到第二个错误,显示功能在输入内。所以该函数的范围仅在 input() 之内。所以你可能有大括号不匹配。就这样吧,

void input(){
    ptr=(struct node *)malloc(sizeof(struct node));
    for(int i=0;i<5;i++){
        printf("enter the elements");
        scanf("%d",&ptr->data);
        ptr->key=i;
        ptr=ptr->next;
    }
}
void display(){
        ptr=head;
        while(ptr!=NULL){
            printf("the linkedlist is --\n");
            printf("%d",ptr->data);
            ptr=ptr->next;
        }
}

所以说到逻辑,你也弄错了。

【讨论】:

    【解决方案2】:
    #include<stdio.h>
    #include<stdlib.h>
    
    struct node {
        int data;
        int key;
        struct node *next;
    };
    struct node * createNode(int data){
        struct node *temp =(struct node *)malloc(sizeof(struct node));
        temp->data = data;
        temp->next = NULL;
    
       return temp;
    }
    struct node * input(){
        int num;
        struct node * head = NULL, *ptr, *list;
    
       for(int i=0;i<5;i++){
          scanf("%d",&num);
          ptr = createNode(num);
          ptr->key=i;  // Why are you using this ?
    
          if(!head){
            list = head = ptr;
          }
          else {
            list = list->next = ptr;
          }
      }
    
      return head;
    
    }
    void display(struct node * head){
      struct node * ptr=head;
      while(ptr!=NULL){
        printf("%d ",ptr->data);
        ptr=ptr->next;
      }
    }
    
    int main(){
        struct node * head = input();
        display(head); 
        return 0;
    }
    

    我已尝试重构您的代码。希望这可以帮助。此外,您可以获得一本关于 C 的好书。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      相关资源
      最近更新 更多