简体   繁体   English

使用 scanf 读入时产生总线错误的程序 - C 程序

[英]Program producing a bus error when reading in using scanf - C Program

I'm writing a program for an employee database and I'm writing the function to add an employee.我正在为员工数据库编写程序,并且正在编写 function 来添加员工。 I'm getting a bus error after my final prompt to scan in info.在我最后提示扫描信息后,我遇到了总线错误。 I'm pretty sure its to do with my scanf statement as I have a print statement right after that is not printing.我很确定这与我的 scanf 语句有关,因为我有一个 print 语句,之后没有打印。 Why would I be getting this error?为什么我会收到此错误?

The prompt in question is for reading in job title.有问题的提示是阅读职位名称。

void addEmployee(void)
{
    char *name;
    char gender;
    int age;
    char *title;

    printf("Enter name: \n");   
    scanf(" %100s", name); 
    scanf("%*[^\n]%*c");

    printf("Enter gender: \n");
    scanf(" %1c", &gender); 
    scanf("%*[^\n]%*c");

    printf("Enter age: \n");
    scanf(" %d", &age); 
    scanf("%*[^\n]%*c");

    printf("Enter job title: \n");
    scanf(" %100s", title); 
    scanf("%*[^\n]%*c");

    printf("Test");
    
    printf("The employee you've entered is: %s %c %d %s \n", name, gender, age, title);

    Employee newEmp = {*name, gender, age, *title};
    
    if(employeeList[0] == NULL)
    {
        employeeList[0] =  &newEmp;
        nodeCount++;
    }
}

Code is passing in an uninitialized pointer.代码传入一个未初始化的指针。

char *name;  // Pointer 'name' not initialize yet.
printf("Enter name: \n");   
// 'name' passed to scanf() is garbage.  
scanf(" %100s", name);

Instead, pass a pointer to an existing array相反,将指针传递给现有数组

char name[100 + 1];
printf("Enter name: \n");   
// Here the array 'name' coverts to the address of the first element of the array.
// scanf receives a valid pointer.
scanf("%100s", name);  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM