首页 文章

C seg故障中的链表

提问于
浏览
1

在下面发布了我的代码的seg fault erros . 我是C的新手,并且遇到了一些麻烦 . 基本上在我的主要部分我创建了一个struct node * head(指向struct节点的指针)并将其赋值为NULL . 然后我将struct node * head发送到push函数,该函数应该将用户定义的整数插入到列表的前面 . 我相信我在推送功能中遇到问题,任何帮助都会非常苛刻 .

〜谢谢

//node.h

struct node{
        int val;
        struct node* next;
 };

 int length(struct node *);
 struct node* push(struct node *, int);
 void print(struct node *, int);


 //node.c

 #include "./node.h"
 #include<stdlib.h>
 #include<stdio.h>

int length(struct node *current){
       if(current->next != NULL)
          return 1 + length(current->next);
       else
          return 1;
}

struct node* push(struct node *head, int num){

   struct node *temp = malloc(sizeof(struct node));
   temp->val = num;
   temp->next = head;
   head = temp;
   return head;
}

void print(struct node* head, int size){
   printf("The list is %i", size);
   printf(" long \n");
   struct node* temp;
   temp = head;
   while(temp != NULL){
   printf("%d", temp->val);
   printf(" ");
   temp = temp->next;
   }
   printf(" \n");
 }


 //main program

 #include "./node.h"
 #include<stdlib.h>
 #include<stdio.h>

  int main(){

    char ans;
    int num;
    struct node* head = NULL;

    do{
       printf("Enter a integer for linked list: ");
       scanf("%d", &num);
       head = push(head, num);
       printf("Add another integer to linked list? (y or n) ");
       scanf("%1s", &ans);
       }while(ans == 'y');

       print(head, length(head));

       return 0;
       }

1 回答

  • 1

    scanf 将使用 %nsn+1 字符读入提供的缓冲区,因为空终止符 .

    使用大小为2的缓冲区( char ans[2]; )并检查第一个字符( ans[0] == 'y' ) . 调用 scanf 时,您也不再需要获取 ans 的地址 .

相关问题