我正在用 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/