c - 分段故障 11,终端中带有 C

标签 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);
}

最佳答案

您需要以下内容:

scanf("%ld", &ssn);

然后

scanf("%ld", &dob);

这是因为您希望 scanf 将数字读入您的变量,您希望它们被此函数更改,所以您给它一个指向这些变量的指针

<小时/>

此外,您最好正确输出数字,使用 %ld 而不是 %d:

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

关于c - 分段故障 11,终端中带有 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37367153/

相关文章:

php - 弱类型语言的优点(和缺点)是什么?

linux - 在 tmux 中卡在覆盖模式

linux - 如何对父目录在 $PATH 中的 bash 脚本进行 sudo?

c++ - 需要帮助解决 C++ 中的 Scanner/Lexer 代码部分中的段错误

c++ - 我试图通过 espeak 传递一些字符串,它会读取它们,但我得到 "segmentation fault"

c++ - Python 列表和 c/c++ 数组

c++ - 当您只能使用 C 文件时,为什么要创建新的头文件?

linux - 如何找出进程正在使用的端口号

objective-c - 如何追踪 Cocoa 应用程序中的段错误?

c - 如何定位字符串中第一次出现的字符串