【问题标题】:(C programming) bus error on my linked list(C 编程)我的链表上的总线错误
【发布时间】:2022-11-13 17:43:38
【问题描述】:

我正在学习使用链表,我觉得我已经理解了这个概念,但是在编码时为什么我总是会出错(总线错误)....这段代码可以运行,但只有在“扫描名称”之后才会出现错误出现。

typedef struct Student{
    char name[20];
    char idNum[10];
    int  saving;

    struct Student *next;
}Student;

Student *head = NULL;

void insert_student(){
    char *name,*idNum;
    int saving;

    Student *current;
    Student *new_student;
    new_student = (Student*)malloc(sizeof(Student));

    // apakah ada memoory kosong?
    if(new_student==NULL){
        printf("==== YOUR MEMMORY IS FULL! ====\n");
        exit(0);
    }

    printf("Enter your name     : ");scanf("%[^\n]s",name);
    printf("Enter your Id       : ");scanf("%[^\n]s",idNum);
    printf("How many your money : Rp");scanf("%d",&saving);

    strcpy(new_student->name,name);
    strcpy(new_student->idNum,idNum);
    new_student->saving = saving;

    new_student->next = NULL;

    if(head==NULL){
        head = new_student;
    }
    else{
        current = head;
        while (current->next != NULL)
        {
            current = current->next;
        }
        current->next = new_student;
    }
}
void print_students(){
    Student *current;

    if(head==NULL){
        printf("==== THERE IS NO STUDENT YET!\n");
        exit(0);
    }
    current = head;
    while (current!= NULL)
    {
        printf("Name   : %s",current->name);
        printf("id     : %s",current->idNum);
        printf("Saving : Rp%d",current->saving);

        current = current->next;
    }
    
}

int main(){
    insert_student();
    print_students();
return 0;
}

我希望为动态链表学生创建节点,然后显示它们

【问题讨论】:

    标签: c data-structures linked-list singly-linked-list


    【解决方案1】:
      printf("Enter your name     : ");scanf("%[^
    ]s",name);
      printf("Enter your Id       : ");scanf("%[^
    ]s",idNum);
    

    在将 namedidNum 的值传递给 scanf 之前,您必须提供有意义的值。相反,您只是将未初始化的垃圾值传递给scanf,这是行不通的。您必须将指针传递给scanf,指向您希望存储正在读取的字符串的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 2015-06-23
      相关资源
      最近更新 更多