2016-05-21 14 views
-3

初めてC言語で自分の言語を教えたり、初めて(Mac)ターミナルを使う方法を学ぶための簡単なプログラムをCで書いています。 しかし、保存するためにscanf()に変数(ssn)を入力しようとすると、セグメント化エラーが発生します。変数をint型からint型に変更して問題を解決しようとしましたが(これは私が調べて、メモリの可用性/アクセスに関係していたと思っていましたが)役に立たないものでした。 私は本当にいくつかの指導に感謝します、ありがとう! 私のコードは以下の通りです:セグメンテーションフォールト11ターミナルでCを使用

/* 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); 
} 
+0

@BLUEPIXYのおかげでその間違いをキャッチするために! – Her

+0

@BLUEPIXY、コメントに私の答えをコピーしてください:-) – ForceBru

+0

@BLUEPIXYありがとう! – Her

答えて

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); 
+0

ありがとう!文字列の入力にもこれを行う必要がありますか? - > scanf( "%s"、名前); – Her

+0

@Her、いいえ、そうではありません。 'scanf'はすでに' name'を 'name'の最初の要素に_aポインタとして認識しています。 – ForceBru

+0

@Her: 'name'は配列として宣言されているので、' name'は既に配列の先頭へのポインタなので、 '&'は必要ありません。配列はC言語では面白く、このような奇妙な方法でポインタと密接に結びついています。 –

関連する問題