终端中带C的分段故障11

时间:2016-05-21 19:26:46

标签: c terminal segmentation-fault

我正在用C编写一个简单的程序,试图第一次自学语言,并且第一次学习使用我的(Mac)终端。 但是,当我尝试将变量(ssn)输入scanf()以保存时,我不断收到分段错误错误。我将变量从int更改为long希望解决问题(我查找并认为与内存可用性/访问有关)但无济于事。 我真的很感激一些指导,谢谢! 我的代码如下:

/* A short example program from cs449 C Programming Text */
/* Section 4.13 */
/* Exercise 4-1 */

/**********************************************************
*                                                         *
*     Write a program to print a name, SSN, and DOB       *
*                                                         *
**********************************************************/

#include <stdio.h>
int main()
{
    char name[20];      /* an array of char used to hold a name */
    long ssn;           /* an integer for holding a 9 dig ssn */
    long dob;           /* an integer for holding a date of birth */

    /* for the name */
    printf("Please enter your name: ");
    scanf("%s", name);

    /* for the SSN */
    printf("Please enter your ssn: ");
    scanf("%ld", ssn);

    /* for the date of birth */
    printf("Please enter your date of birth:\n");
    printf("Ex. monthdayyear or 041293\n");
    scanf("%ld", dob);

    /* final print of user-entered information */
    printf("You are %s born on %d and your SSN is %d", name, dob, ssn); 

    /* remember to always return 0 at the end of a main funct! */
    return(0);
}

1 个答案:

答案 0 :(得分:0)

您需要以下内容:

scanf("%ld", &ssn);

然后

scanf("%ld", &dob);

这是因为您希望scanf将数字读入您的变量,您希望通过此函数更改,因此您可以将其更改为 指针指向这些变量。

此外,您最好使用%ld代替%d正确输出数字:

printf("You are %s born on %ld and your SSN is %ld", name, dob, ssn);