【问题标题】:Segmentation Fault 11 with C in Terminal终端中带有 C 的分段故障 11
【发布时间】:2016-05-21 19:26:45
【问题描述】:

我正在用 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);
}

【问题讨论】:

  • @BLUEPIXY 感谢您发现这个错误!
  • @BLUEPIXY,把我的答案复制到 cmets :-)
  • @BLUEPIXY 非常感谢!
  • @BLUEPIXY,我只是在开玩笑,伙计,因为你说的是​​完全我在回答中所说的即使是在相同的顺序:)
  • 回滚。您不得编辑使现有答案无用的问题!

标签: c terminal segmentation-fault


【解决方案1】:

您需要以下内容:

scanf("%ld", &ssn);

然后

scanf("%ld", &dob);

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


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

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

【讨论】:

  • 谢谢!我是否也需要对字符串输入执行此操作? --> scanf("%s", name);
  • @Her,不,你不知道,scanf 已经将name 视为指针,指向name 的第一个元素。
  • @Her:因为name被声明为一个数组,name已经是一个指向数组开头的指针,所以你不需要&amp;。数组在 C 中很有趣,并且以这种奇怪的方式与指针密切相关。
  • @ChrisDodd: "因为 ...name 已经是指向数组开头的指针..." - 不! 对于大多数人来说,它会衰减到这样的指针用途,包括这里的用法,但它一个数组,而不是一个指针。
  • @Olaf:这取决于上下文——在这个(和大多数)上下文中,对应声明具有数组类型的标识符指针。说它“衰变”只是承认问题——不涉及额外的运行时开销或转换。
猜你喜欢
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多